blob: 04467a4fa884e2349e053426bf272f66eeb30a42 [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"
Richard Smithbf5bcf22018-06-26 23:20:26 +000022#include "clang/Basic/BitmaskEnum.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/ADT/ArrayRef.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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037/// Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000038class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
39public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000040 /// Kinds of OpenMP regions used in codegen.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000041 enum CGOpenMPRegionKind {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// Region with outlined function for standalone 'parallel'
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000043 /// directive.
44 ParallelOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Region with outlined function for standalone 'task' directive.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 TaskOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000047 /// Region for constructs that do not require function outlining,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000048 /// like 'for', 'sections', 'atomic' etc. directives.
49 InlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000050 /// Region with outlined function for standalone 'target' directive.
Samuel Antaobed3c462015-10-02 16:14:20 +000051 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000067 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000074 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000099/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000112 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000113 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000116 /// 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:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000126 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev18095712014-10-10 12:19:54 +0000127 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000132/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000193 /// Get a variable or parameter for storing global thread id
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000197 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000200 /// Get the name of the capture helper.
Alexey Bataev62b63b12015-03-10 07:28:44 +0000201 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:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000214 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev62b63b12015-03-10 07:28:44 +0000215 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221/// API for inlined captured statement code generation in OpenMP
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000222/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000232 // 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000247 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000262 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000270 /// Get an LValue for the current ThreadID variable.
Alexey Bataev311a9282017-10-12 13:51:32 +0000271 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
272 if (OuterRegionInfo)
273 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
274 llvm_unreachable("No LValue for inlined OpenMP construct");
275 }
276
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000277 /// 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:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000299 /// CodeGen info about outer OpenMP region.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000300 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
301 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000302};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000304/// API for captured statement code generation in OpenMP target
Samuel Antaobed3c462015-10-02 16:14:20 +0000305/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000317 /// This is unused for target regions because each starts executing
Samuel Antaobed3c462015-10-02 16:14:20 +0000318 /// with a single thread.
319 const VarDecl *getThreadIDVariable() const override { return nullptr; }
320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000321 /// 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}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000336/// API for generation of expressions captured in a innermost OpenMP
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000366 /// Lookup the captured field decl for a variable.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000367 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000373 /// Emit the captured statement body.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000374 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
375 llvm_unreachable("No body for expressions");
376 }
377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000378 /// Get a variable or parameter for storing global thread id
Samuel Antaob68e2db2016-03-03 16:20:23 +0000379 /// inside OpenMP construct.
380 const VarDecl *getThreadIDVariable() const override {
381 llvm_unreachable("No thread id for expressions");
382 }
383
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000384 /// Get the name of the capture helper.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000385 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000396/// RAII for emitting code of OpenMP constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000397class 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:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000404 /// Constructs region for combined constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000405 /// \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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000433/// Values for bit flags used in the ident_t to describe the fields.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000434/// 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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Use trampoline for internal microtask.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000438 OMP_IDENT_IMD = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000439 /// Use c-style ident structure.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000440 OMP_IDENT_KMPC = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000441 /// Atomic reduction option for kmpc_reduce.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000442 OMP_ATOMIC_REDUCE = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000443 /// Explicit 'barrier' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000444 OMP_IDENT_BARRIER_EXPL = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445 /// Implicit barrier in code.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000446 OMP_IDENT_BARRIER_IMPL = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// Implicit barrier in 'for' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000448 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000449 /// Implicit barrier in 'sections' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000450 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000451 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000462/// Describes ident structure that describes a source location.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000463/// 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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000489 /// might be used in Fortran
Alexey Bataev50b3c952016-02-19 10:38:26 +0000490 IdentField_Reserved_1,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000491 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000492 IdentField_Flags,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Not really used in Fortran any more
Alexey Bataev50b3c952016-02-19 10:38:26 +0000494 IdentField_Reserved_2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// Source[4] in Fortran, do not use for C++
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 IdentField_Reserved_3,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000497 /// String describing the source location. The string is composed of
Alexey Bataev50b3c952016-02-19 10:38:26 +0000498 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000503/// Schedule types for 'omp for' loops (these enumerators are taken from
Alexey Bataev50b3c952016-02-19 10:38:26 +0000504/// the enum sched_type in kmp.h).
505enum OpenMPSchedType {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000506 /// Lower bound for default (unordered) versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000507 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,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000516 /// Lower bound for 'ordered' versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000517 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,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000525 /// dist_schedule types
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000526 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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000536 /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000537 /// kmpc_micro microtask, ...);
538 OMPRTL__kmpc_fork_call,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000539 /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000540 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
541 OMPRTL__kmpc_threadprivate_cached,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Call to void __kmpc_threadprivate_register( ident_t *,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000543 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811/// Emit initialization of arrays of complex types.
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000812/// \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
900LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000901 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000902}
903
904LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
905 const Expr *E) {
906 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
907 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
908 return LValue();
909}
910
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000911void ReductionCodeGen::emitAggregateInitialization(
912 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
913 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000914 // Emit VarDecl with copy init for arrays.
915 // Get the address of the original variable captured in current
916 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000917 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000918 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000919 bool EmitDeclareReductionInit =
920 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000921 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000922 EmitDeclareReductionInit,
923 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
924 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000925 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000926}
927
928ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
929 ArrayRef<const Expr *> Privates,
930 ArrayRef<const Expr *> ReductionOps) {
931 ClausesData.reserve(Shareds.size());
932 SharedAddresses.reserve(Shareds.size());
933 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000934 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000935 auto IPriv = Privates.begin();
936 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000937 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000938 ClausesData.emplace_back(Ref, *IPriv, *IRed);
939 std::advance(IPriv, 1);
940 std::advance(IRed, 1);
941 }
942}
943
944void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
945 assert(SharedAddresses.size() == N &&
946 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000947 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
948 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
949 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000950}
951
952void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000953 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
955 QualType PrivateType = PrivateVD->getType();
956 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000957 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000958 Sizes.emplace_back(
959 CGF.getTypeSize(
960 SharedAddresses[N].first.getType().getNonReferenceType()),
961 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000962 return;
963 }
964 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000965 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000966 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000967 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
968 ->getElementType();
969 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000970 if (AsArraySection) {
971 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
972 SharedAddresses[N].first.getPointer());
973 Size = CGF.Builder.CreateNUWAdd(
974 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000975 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000976 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000977 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000978 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000979 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000980 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000981 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000982 CodeGenFunction::OpaqueValueMapping OpaqueMap(
983 CGF,
984 cast<OpaqueValueExpr>(
985 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
986 RValue::get(Size));
987 CGF.EmitVariablyModifiedType(PrivateType);
988}
989
990void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
991 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000992 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000993 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
994 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000995 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000996 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000997 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000998 "items.");
999 return;
1000 }
1001 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::emitInitialization(
1010 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1011 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1012 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001013 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001014 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001015 const OMPDeclareReductionDecl *DRD =
1016 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001017 QualType PrivateType = PrivateVD->getType();
1018 PrivateAddr = CGF.Builder.CreateElementBitCast(
1019 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1020 QualType SharedType = SharedAddresses[N].first.getType();
1021 SharedLVal = CGF.MakeAddrLValue(
1022 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1023 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001024 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001025 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001026 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001027 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001028 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1029 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1030 PrivateAddr, SharedLVal.getAddress(),
1031 SharedLVal.getType());
1032 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1033 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1034 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1035 PrivateVD->getType().getQualifiers(),
1036 /*IsInitializer=*/false);
1037 }
1038}
1039
1040bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001041 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001042 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1043 QualType PrivateType = PrivateVD->getType();
1044 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1045 return DTorKind != QualType::DK_none;
1046}
1047
1048void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1049 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001050 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001051 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1052 QualType PrivateType = PrivateVD->getType();
1053 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1054 if (needCleanups(N)) {
1055 PrivateAddr = CGF.Builder.CreateElementBitCast(
1056 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1057 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1058 }
1059}
1060
1061static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1062 LValue BaseLV) {
1063 BaseTy = BaseTy.getNonReferenceType();
1064 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1065 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001066 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001067 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001068 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001069 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1070 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001071 }
1072 BaseTy = BaseTy->getPointeeType();
1073 }
1074 return CGF.MakeAddrLValue(
1075 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1076 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001077 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001078 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001079}
1080
1081static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1082 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1083 llvm::Value *Addr) {
1084 Address Tmp = Address::invalid();
1085 Address TopTmp = Address::invalid();
1086 Address MostTopTmp = Address::invalid();
1087 BaseTy = BaseTy.getNonReferenceType();
1088 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1089 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1090 Tmp = CGF.CreateMemTemp(BaseTy);
1091 if (TopTmp.isValid())
1092 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1093 else
1094 MostTopTmp = Tmp;
1095 TopTmp = Tmp;
1096 BaseTy = BaseTy->getPointeeType();
1097 }
1098 llvm::Type *Ty = BaseLVType;
1099 if (Tmp.isValid())
1100 Ty = Tmp.getElementType();
1101 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1102 if (Tmp.isValid()) {
1103 CGF.Builder.CreateStore(Addr, Tmp);
1104 return MostTopTmp;
1105 }
1106 return Address(Addr, BaseLVAlignment);
1107}
1108
Alexey Bataev1c44e152018-03-06 18:59:43 +00001109static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001110 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001111 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1112 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1113 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001114 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001115 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 Base = TempASE->getBase()->IgnoreParenImpCasts();
1117 DE = cast<DeclRefExpr>(Base);
1118 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001119 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1120 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1121 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001122 Base = TempASE->getBase()->IgnoreParenImpCasts();
1123 DE = cast<DeclRefExpr>(Base);
1124 OrigVD = cast<VarDecl>(DE->getDecl());
1125 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001126 return OrigVD;
1127}
1128
1129Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1130 Address PrivateAddr) {
1131 const DeclRefExpr *DE;
1132 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001133 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001134 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 LValue BaseLValue =
1136 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1137 OriginalBaseLValue);
1138 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1139 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001140 llvm::Value *PrivatePointer =
1141 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1142 PrivateAddr.getPointer(),
1143 SharedAddresses[N].first.getAddress().getType());
1144 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001145 return castToBase(CGF, OrigVD->getType(),
1146 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001147 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001148 OriginalBaseLValue.getAlignment(), Ptr);
1149 }
1150 BaseDecls.emplace_back(
1151 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1152 return PrivateAddr;
1153}
1154
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001155bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001156 const OMPDeclareReductionDecl *DRD =
1157 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001158 return DRD && DRD->getInitializer();
1159}
1160
Alexey Bataev18095712014-10-10 12:19:54 +00001161LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001162 return CGF.EmitLoadOfPointerLValue(
1163 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1164 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001165}
1166
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001167void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001168 if (!CGF.HaveInsertPoint())
1169 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001170 // 1.2.2 OpenMP Language Terminology
1171 // Structured block - An executable statement with a single entry at the
1172 // top and a single exit at the bottom.
1173 // The point of exit cannot be a branch out of the structured block.
1174 // longjmp() and throw() must not violate the entry/exit criteria.
1175 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001176 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001177 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001178}
1179
Alexey Bataev62b63b12015-03-10 07:28:44 +00001180LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1181 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001182 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1183 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001184 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001185}
1186
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001187static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1188 QualType FieldTy) {
1189 auto *Field = FieldDecl::Create(
1190 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1191 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1192 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1193 Field->setAccess(AS_public);
1194 DC->addDecl(Field);
1195 return Field;
1196}
1197
Alexey Bataev18fa2322018-05-02 14:20:50 +00001198CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1199 StringRef Separator)
1200 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1201 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001202 ASTContext &C = CGM.getContext();
1203 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1204 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1205 RD->startDefinition();
1206 // reserved_1
1207 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1208 // flags
1209 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1210 // reserved_2
1211 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1212 // reserved_3
1213 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1214 // psource
1215 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1216 RD->completeDefinition();
1217 IdentQTy = C.getRecordType(RD);
1218 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001219 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001220
1221 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001222}
1223
Alexey Bataev91797552015-03-18 04:13:55 +00001224void CGOpenMPRuntime::clear() {
1225 InternalVars.clear();
1226}
1227
Alexey Bataev18fa2322018-05-02 14:20:50 +00001228std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1229 SmallString<128> Buffer;
1230 llvm::raw_svector_ostream OS(Buffer);
1231 StringRef Sep = FirstSeparator;
1232 for (StringRef Part : Parts) {
1233 OS << Sep << Part;
1234 Sep = Separator;
1235 }
1236 return OS.str();
1237}
1238
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001239static llvm::Function *
1240emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1241 const Expr *CombinerInitializer, const VarDecl *In,
1242 const VarDecl *Out, bool IsCombiner) {
1243 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001244 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001245 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1246 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001247 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001248 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001249 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001250 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001251 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001252 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001253 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001254 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001255 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001256 std::string Name = CGM.getOpenMPRuntime().getName(
1257 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1258 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1259 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001260 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001261 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001262 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001263 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001264 CodeGenFunction CGF(CGM);
1265 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1266 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001267 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1268 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001269 CodeGenFunction::OMPPrivateScope Scope(CGF);
1270 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001271 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001272 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1273 .getAddress();
1274 });
1275 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001276 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001277 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1278 .getAddress();
1279 });
1280 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001281 if (!IsCombiner && Out->hasInit() &&
1282 !CGF.isTrivialInitializer(Out->getInit())) {
1283 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1284 Out->getType().getQualifiers(),
1285 /*IsInitializer=*/true);
1286 }
1287 if (CombinerInitializer)
1288 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001289 Scope.ForceCleanup();
1290 CGF.FinishFunction();
1291 return Fn;
1292}
1293
1294void CGOpenMPRuntime::emitUserDefinedReduction(
1295 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1296 if (UDRMap.count(D) > 0)
1297 return;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001298 llvm::Function *Combiner = emitCombinerOrInitializer(
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001299 CGM, D->getType(), D->getCombiner(),
1300 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1301 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001302 /*IsCombiner=*/true);
1303 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001304 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001305 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001306 CGM, D->getType(),
1307 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1308 : nullptr,
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001309 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1310 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001311 /*IsCombiner=*/false);
1312 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001313 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001314 if (CGF) {
1315 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1316 Decls.second.push_back(D);
1317 }
1318}
1319
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001320std::pair<llvm::Function *, llvm::Function *>
1321CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1322 auto I = UDRMap.find(D);
1323 if (I != UDRMap.end())
1324 return I->second;
1325 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1326 return UDRMap.lookup(D);
1327}
1328
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001329static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1330 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1331 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1332 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001333 assert(ThreadIDVar->getType()->isPointerType() &&
1334 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001335 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001336 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001337 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001338 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001339 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001340 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001341 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001342 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001343 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001344 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001345 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001346 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001347 else if (const auto *OPFD =
1348 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001349 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001350 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001351 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1352 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001353 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001354 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001355 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001356 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001357}
1358
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001359llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1360 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1361 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1362 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1363 return emitParallelOrTeamsOutlinedFunction(
1364 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1365}
1366
1367llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1368 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1369 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1370 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1371 return emitParallelOrTeamsOutlinedFunction(
1372 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1373}
1374
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001375llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1376 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001377 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1378 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1379 bool Tied, unsigned &NumberOfParts) {
1380 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1381 PrePostActionTy &) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001382 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1383 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001384 llvm::Value *TaskArgs[] = {
1385 UpLoc, ThreadID,
1386 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1387 TaskTVar->getType()->castAs<PointerType>())
1388 .getPointer()};
1389 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1390 };
1391 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1392 UntiedCodeGen);
1393 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001394 assert(!ThreadIDVar->getType()->isPointerType() &&
1395 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001396 const OpenMPDirectiveKind Region =
1397 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1398 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001399 const CapturedStmt *CS = D.getCapturedStmt(Region);
1400 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001401 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001402 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1403 InnermostKind,
1404 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001405 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001406 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001407 if (!Tied)
1408 NumberOfParts = Action.getNumberOfParts();
1409 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001410}
1411
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001412static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1413 const RecordDecl *RD, const CGRecordLayout &RL,
1414 ArrayRef<llvm::Constant *> Data) {
1415 llvm::StructType *StructTy = RL.getLLVMType();
1416 unsigned PrevIdx = 0;
1417 ConstantInitBuilder CIBuilder(CGM);
1418 auto DI = Data.begin();
1419 for (const FieldDecl *FD : RD->fields()) {
1420 unsigned Idx = RL.getLLVMFieldNo(FD);
1421 // Fill the alignment.
1422 for (unsigned I = PrevIdx; I < Idx; ++I)
1423 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1424 PrevIdx = Idx + 1;
1425 Fields.add(*DI);
1426 ++DI;
1427 }
1428}
1429
1430template <class... As>
1431static llvm::GlobalVariable *
Mike Ricee1ca7b62018-08-29 15:45:11 +00001432createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
1433 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1434 As &&... Args) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001435 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1436 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1437 ConstantInitBuilder CIBuilder(CGM);
1438 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1439 buildStructValue(Fields, CGM, RD, RL, Data);
1440 return Fields.finishAndCreateGlobal(
Mike Ricee1ca7b62018-08-29 15:45:11 +00001441 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
1442 std::forward<As>(Args)...);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001443}
1444
1445template <typename T>
Benjamin Kramer651d0bf2018-05-15 21:26:47 +00001446static void
1447createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1448 ArrayRef<llvm::Constant *> Data,
1449 T &Parent) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001450 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1451 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1452 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1453 buildStructValue(Fields, CGM, RD, RL, Data);
1454 Fields.finishAndAddTo(Parent);
1455}
1456
Alexey Bataev50b3c952016-02-19 10:38:26 +00001457Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001458 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001459 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001460 if (!Entry) {
1461 if (!DefaultOpenMPPSource) {
1462 // Initialize default location for psource field of ident_t structure of
1463 // all ident_t objects. Format is ";file;function;line;column;;".
1464 // Taken from
1465 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1466 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001467 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001468 DefaultOpenMPPSource =
1469 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1470 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001471
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001472 llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1473 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1474 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1475 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1476 DefaultOpenMPPSource};
Mike Ricee1ca7b62018-08-29 15:45:11 +00001477 llvm::GlobalValue *DefaultOpenMPLocation =
1478 createGlobalStruct(CGM, IdentQTy, /*IsConstant=*/false, Data, "",
1479 llvm::GlobalValue::PrivateLinkage);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001480 DefaultOpenMPLocation->setUnnamedAddr(
1481 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001482
John McCall7f416cc2015-09-08 08:05:57 +00001483 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001484 }
John McCall7f416cc2015-09-08 08:05:57 +00001485 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001486}
1487
Alexey Bataevfd006c42018-10-05 15:08:53 +00001488void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
1489 bool AtCurrentPoint) {
1490 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1491 assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
1492
1493 llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1494 if (AtCurrentPoint) {
1495 Elem.second.ServiceInsertPt = new llvm::BitCastInst(
1496 Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
1497 } else {
1498 Elem.second.ServiceInsertPt =
1499 new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1500 Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
1501 }
1502}
1503
1504void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
1505 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1506 if (Elem.second.ServiceInsertPt) {
1507 llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
1508 Elem.second.ServiceInsertPt = nullptr;
1509 Ptr->eraseFromParent();
1510 }
1511}
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
Alexey Bataevfd006c42018-10-05 15:08:53 +00001539 if (!Elem.second.ServiceInsertPt)
1540 setLocThreadIdInsertPt(CGF);
Alexey Bataev9959db52014-05-06 10:08:46 +00001541 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001542 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001543 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001544 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001545 }
1546
1547 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001548 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1549 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1550 LValue PSource =
1551 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001552
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001553 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001554 if (OMPDebugLoc == nullptr) {
1555 SmallString<128> Buffer2;
1556 llvm::raw_svector_ostream OS2(Buffer2);
1557 // Build debug location
1558 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1559 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001560 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001561 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001562 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1563 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1564 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001565 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001566 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001567 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001568
John McCall7f416cc2015-09-08 08:05:57 +00001569 // Our callers always pass this to a runtime function, so for
1570 // convenience, go ahead and return a naked pointer.
1571 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001572}
1573
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001574llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1575 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001576 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1577
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001578 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001579 // Check whether we've already cached a load of the thread id in this
1580 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001581 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001582 if (I != OpenMPLocThreadIDMap.end()) {
1583 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001584 if (ThreadID != nullptr)
1585 return ThreadID;
1586 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001587 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001588 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1589 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001590 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001591 if (auto *OMPRegionInfo =
1592 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1593 if (OMPRegionInfo->getThreadIDVariable()) {
1594 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001595 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001596 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001597 // If value loaded in entry block, cache it and use it everywhere in
1598 // function.
1599 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1600 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1601 Elem.second.ThreadID = ThreadID;
1602 }
1603 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001604 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001605 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001606 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001607
1608 // This is not an outlined function region - need to call __kmpc_int32
1609 // kmpc_global_thread_num(ident_t *loc).
1610 // Generate thread id value and cache this value for use across the
1611 // function.
Alexey Bataevfd006c42018-10-05 15:08:53 +00001612 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1613 if (!Elem.second.ServiceInsertPt)
1614 setLocThreadIdInsertPt(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001615 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001616 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001617 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001618 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1619 emitUpdateLocation(CGF, Loc));
1620 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001621 Elem.second.ThreadID = Call;
1622 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001623}
1624
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001625void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001626 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataevfd006c42018-10-05 15:08:53 +00001627 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1628 clearLocThreadIdInsertPt(CGF);
Alexey Bataev03b340a2014-10-21 03:16:40 +00001629 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001630 }
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001631 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001632 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001633 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001634 FunctionUDRMap.erase(CGF.CurFn);
1635 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001636}
1637
1638llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001639 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001640}
1641
1642llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001643 if (!Kmpc_MicroTy) {
1644 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1645 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1646 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1647 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1648 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001649 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1650}
1651
1652llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001653CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001654 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001655 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001656 case OMPRTL__kmpc_fork_call: {
1657 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1658 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001659 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1660 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001661 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001662 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001663 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1664 break;
1665 }
1666 case OMPRTL__kmpc_global_thread_num: {
1667 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001668 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001669 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001670 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001671 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1672 break;
1673 }
Alexey Bataev97720002014-11-11 04:05:39 +00001674 case OMPRTL__kmpc_threadprivate_cached: {
1675 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1676 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1677 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1678 CGM.VoidPtrTy, CGM.SizeTy,
1679 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001680 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001681 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1682 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1683 break;
1684 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001685 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001686 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1687 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001688 llvm::Type *TypeParams[] = {
1689 getIdentTyPointerTy(), CGM.Int32Ty,
1690 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001691 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001692 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1693 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1694 break;
1695 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001696 case OMPRTL__kmpc_critical_with_hint: {
1697 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1698 // kmp_critical_name *crit, uintptr_t hint);
1699 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1700 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1701 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001702 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001703 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1704 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1705 break;
1706 }
Alexey Bataev97720002014-11-11 04:05:39 +00001707 case OMPRTL__kmpc_threadprivate_register: {
1708 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1709 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1710 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001711 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001712 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1713 /*isVarArg*/ false)->getPointerTo();
1714 // typedef void *(*kmpc_cctor)(void *, void *);
1715 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001716 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001717 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001718 /*isVarArg*/ false)
1719 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001720 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001721 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001722 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1723 ->getPointerTo();
1724 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1725 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001726 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001727 /*isVarArg*/ false);
1728 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1729 break;
1730 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001731 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001732 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1733 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001734 llvm::Type *TypeParams[] = {
1735 getIdentTyPointerTy(), CGM.Int32Ty,
1736 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001737 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001738 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1739 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1740 break;
1741 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001742 case OMPRTL__kmpc_cancel_barrier: {
1743 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1744 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001745 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001746 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001747 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1748 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001749 break;
1750 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001751 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001752 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001753 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001754 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001755 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1756 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1757 break;
1758 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001759 case OMPRTL__kmpc_for_static_fini: {
1760 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1761 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001762 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001763 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1764 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1765 break;
1766 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001767 case OMPRTL__kmpc_push_num_threads: {
1768 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1769 // kmp_int32 num_threads)
1770 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1771 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001772 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001773 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1774 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1775 break;
1776 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001777 case OMPRTL__kmpc_serialized_parallel: {
1778 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1779 // global_tid);
1780 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001781 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001782 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1783 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1784 break;
1785 }
1786 case OMPRTL__kmpc_end_serialized_parallel: {
1787 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1788 // global_tid);
1789 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001790 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001791 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1792 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1793 break;
1794 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001795 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001796 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001797 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001798 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001799 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001800 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1801 break;
1802 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001803 case OMPRTL__kmpc_master: {
1804 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1805 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001806 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001807 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1808 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1809 break;
1810 }
1811 case OMPRTL__kmpc_end_master: {
1812 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1813 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001814 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001815 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1816 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1817 break;
1818 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001819 case OMPRTL__kmpc_omp_taskyield: {
1820 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1821 // int end_part);
1822 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001823 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001824 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1825 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1826 break;
1827 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001828 case OMPRTL__kmpc_single: {
1829 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1830 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001831 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001832 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1833 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1834 break;
1835 }
1836 case OMPRTL__kmpc_end_single: {
1837 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1838 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001839 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001840 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1841 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1842 break;
1843 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001844 case OMPRTL__kmpc_omp_task_alloc: {
1845 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1846 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1847 // kmp_routine_entry_t *task_entry);
1848 assert(KmpRoutineEntryPtrTy != nullptr &&
1849 "Type kmp_routine_entry_t must be created.");
1850 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1851 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1852 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001853 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001854 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1855 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1856 break;
1857 }
1858 case OMPRTL__kmpc_omp_task: {
1859 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1860 // *new_task);
1861 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1862 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001863 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001864 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1865 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1866 break;
1867 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001868 case OMPRTL__kmpc_copyprivate: {
1869 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001870 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001871 // kmp_int32 didit);
1872 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1873 auto *CpyFnTy =
1874 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001875 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001876 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1877 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001878 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001879 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1880 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1881 break;
1882 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001883 case OMPRTL__kmpc_reduce: {
1884 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1885 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1886 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1887 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1888 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1889 /*isVarArg=*/false);
1890 llvm::Type *TypeParams[] = {
1891 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1892 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1893 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001894 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001895 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1896 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1897 break;
1898 }
1899 case OMPRTL__kmpc_reduce_nowait: {
1900 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1901 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1902 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1903 // *lck);
1904 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1905 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1906 /*isVarArg=*/false);
1907 llvm::Type *TypeParams[] = {
1908 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1909 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1910 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001911 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001912 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1913 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1914 break;
1915 }
1916 case OMPRTL__kmpc_end_reduce: {
1917 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1918 // kmp_critical_name *lck);
1919 llvm::Type *TypeParams[] = {
1920 getIdentTyPointerTy(), CGM.Int32Ty,
1921 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001922 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001923 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1924 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1925 break;
1926 }
1927 case OMPRTL__kmpc_end_reduce_nowait: {
1928 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1929 // kmp_critical_name *lck);
1930 llvm::Type *TypeParams[] = {
1931 getIdentTyPointerTy(), CGM.Int32Ty,
1932 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001933 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001934 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1935 RTLFn =
1936 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1937 break;
1938 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001939 case OMPRTL__kmpc_omp_task_begin_if0: {
1940 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1941 // *new_task);
1942 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1943 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001944 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001945 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1946 RTLFn =
1947 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1948 break;
1949 }
1950 case OMPRTL__kmpc_omp_task_complete_if0: {
1951 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1952 // *new_task);
1953 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1954 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001955 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001956 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1957 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1958 /*Name=*/"__kmpc_omp_task_complete_if0");
1959 break;
1960 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001961 case OMPRTL__kmpc_ordered: {
1962 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1963 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001964 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001965 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1966 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1967 break;
1968 }
1969 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001970 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001971 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001972 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001973 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1974 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1975 break;
1976 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001977 case OMPRTL__kmpc_omp_taskwait: {
1978 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1979 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001980 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001981 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1982 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1983 break;
1984 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001985 case OMPRTL__kmpc_taskgroup: {
1986 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1987 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001988 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001989 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1990 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1991 break;
1992 }
1993 case OMPRTL__kmpc_end_taskgroup: {
1994 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1995 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001996 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001997 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1998 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1999 break;
2000 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00002001 case OMPRTL__kmpc_push_proc_bind: {
2002 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
2003 // int proc_bind)
2004 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002005 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002006 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2007 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2008 break;
2009 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002010 case OMPRTL__kmpc_omp_task_with_deps: {
2011 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2012 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2013 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2014 llvm::Type *TypeParams[] = {
2015 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2016 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002017 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002018 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2019 RTLFn =
2020 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2021 break;
2022 }
2023 case OMPRTL__kmpc_omp_wait_deps: {
2024 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2025 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2026 // kmp_depend_info_t *noalias_dep_list);
2027 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2028 CGM.Int32Ty, CGM.VoidPtrTy,
2029 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002030 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002031 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2032 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2033 break;
2034 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002035 case OMPRTL__kmpc_cancellationpoint: {
2036 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2037 // global_tid, kmp_int32 cncl_kind)
2038 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002039 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002040 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2041 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2042 break;
2043 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002044 case OMPRTL__kmpc_cancel: {
2045 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2046 // kmp_int32 cncl_kind)
2047 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002048 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002049 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2050 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2051 break;
2052 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002053 case OMPRTL__kmpc_push_num_teams: {
2054 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2055 // kmp_int32 num_teams, kmp_int32 num_threads)
2056 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2057 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002058 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002059 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2060 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2061 break;
2062 }
2063 case OMPRTL__kmpc_fork_teams: {
2064 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2065 // microtask, ...);
2066 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2067 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002068 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002069 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2070 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2071 break;
2072 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002073 case OMPRTL__kmpc_taskloop: {
2074 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2075 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2076 // sched, kmp_uint64 grainsize, void *task_dup);
2077 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2078 CGM.IntTy,
2079 CGM.VoidPtrTy,
2080 CGM.IntTy,
2081 CGM.Int64Ty->getPointerTo(),
2082 CGM.Int64Ty->getPointerTo(),
2083 CGM.Int64Ty,
2084 CGM.IntTy,
2085 CGM.IntTy,
2086 CGM.Int64Ty,
2087 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002088 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002089 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2090 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2091 break;
2092 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002093 case OMPRTL__kmpc_doacross_init: {
2094 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2095 // num_dims, struct kmp_dim *dims);
2096 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2097 CGM.Int32Ty,
2098 CGM.Int32Ty,
2099 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002100 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002101 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2102 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2103 break;
2104 }
2105 case OMPRTL__kmpc_doacross_fini: {
2106 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2107 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002108 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002109 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2110 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2111 break;
2112 }
2113 case OMPRTL__kmpc_doacross_post: {
2114 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2115 // *vec);
2116 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2117 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002118 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002119 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2120 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2121 break;
2122 }
2123 case OMPRTL__kmpc_doacross_wait: {
2124 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2125 // *vec);
2126 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2127 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002128 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002129 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2130 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2131 break;
2132 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002133 case OMPRTL__kmpc_task_reduction_init: {
2134 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2135 // *data);
2136 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002137 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002138 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2139 RTLFn =
2140 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2141 break;
2142 }
2143 case OMPRTL__kmpc_task_reduction_get_th_data: {
2144 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2145 // *d);
2146 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002147 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002148 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2149 RTLFn = CGM.CreateRuntimeFunction(
2150 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2151 break;
2152 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002153 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002154 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2155 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002156 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002157 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002158 CGM.VoidPtrTy,
2159 CGM.Int32Ty,
2160 CGM.VoidPtrPtrTy,
2161 CGM.VoidPtrPtrTy,
2162 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002163 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002164 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002165 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2166 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2167 break;
2168 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002169 case OMPRTL__tgt_target_nowait: {
2170 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2171 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2172 // int64_t *arg_types);
2173 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2174 CGM.VoidPtrTy,
2175 CGM.Int32Ty,
2176 CGM.VoidPtrPtrTy,
2177 CGM.VoidPtrPtrTy,
2178 CGM.SizeTy->getPointerTo(),
2179 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002180 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002181 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2182 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2183 break;
2184 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002185 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002186 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002187 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002188 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2189 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002190 CGM.VoidPtrTy,
2191 CGM.Int32Ty,
2192 CGM.VoidPtrPtrTy,
2193 CGM.VoidPtrPtrTy,
2194 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002195 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002196 CGM.Int32Ty,
2197 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002198 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002199 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2200 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2201 break;
2202 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002203 case OMPRTL__tgt_target_teams_nowait: {
2204 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2205 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2206 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2207 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2208 CGM.VoidPtrTy,
2209 CGM.Int32Ty,
2210 CGM.VoidPtrPtrTy,
2211 CGM.VoidPtrPtrTy,
2212 CGM.SizeTy->getPointerTo(),
2213 CGM.Int64Ty->getPointerTo(),
2214 CGM.Int32Ty,
2215 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002216 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002217 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2218 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2219 break;
2220 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002221 case OMPRTL__tgt_register_lib: {
2222 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2223 QualType ParamTy =
2224 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2225 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002226 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002227 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2228 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2229 break;
2230 }
2231 case OMPRTL__tgt_unregister_lib: {
2232 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2233 QualType ParamTy =
2234 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2235 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002236 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002237 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2238 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2239 break;
2240 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002241 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002242 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2243 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2244 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002245 CGM.Int32Ty,
2246 CGM.VoidPtrPtrTy,
2247 CGM.VoidPtrPtrTy,
2248 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002249 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002250 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002251 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2252 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2253 break;
2254 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002255 case OMPRTL__tgt_target_data_begin_nowait: {
2256 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2257 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2258 // *arg_types);
2259 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2260 CGM.Int32Ty,
2261 CGM.VoidPtrPtrTy,
2262 CGM.VoidPtrPtrTy,
2263 CGM.SizeTy->getPointerTo(),
2264 CGM.Int64Ty->getPointerTo()};
2265 auto *FnTy =
2266 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2267 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2268 break;
2269 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002270 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002271 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2272 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2273 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002274 CGM.Int32Ty,
2275 CGM.VoidPtrPtrTy,
2276 CGM.VoidPtrPtrTy,
2277 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002278 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002279 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002280 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2281 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2282 break;
2283 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002284 case OMPRTL__tgt_target_data_end_nowait: {
2285 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2286 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2287 // *arg_types);
2288 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2289 CGM.Int32Ty,
2290 CGM.VoidPtrPtrTy,
2291 CGM.VoidPtrPtrTy,
2292 CGM.SizeTy->getPointerTo(),
2293 CGM.Int64Ty->getPointerTo()};
2294 auto *FnTy =
2295 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2296 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2297 break;
2298 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002299 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002300 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2301 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2302 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002303 CGM.Int32Ty,
2304 CGM.VoidPtrPtrTy,
2305 CGM.VoidPtrPtrTy,
2306 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002307 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002308 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002309 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2310 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2311 break;
2312 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002313 case OMPRTL__tgt_target_data_update_nowait: {
2314 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2315 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2316 // *arg_types);
2317 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2318 CGM.Int32Ty,
2319 CGM.VoidPtrPtrTy,
2320 CGM.VoidPtrPtrTy,
2321 CGM.SizeTy->getPointerTo(),
2322 CGM.Int64Ty->getPointerTo()};
2323 auto *FnTy =
2324 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2325 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2326 break;
2327 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002328 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002329 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002330 return RTLFn;
2331}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002332
Alexander Musman21212e42015-03-13 10:38:23 +00002333llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2334 bool IVSigned) {
2335 assert((IVSize == 32 || IVSize == 64) &&
2336 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002337 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2338 : "__kmpc_for_static_init_4u")
2339 : (IVSigned ? "__kmpc_for_static_init_8"
2340 : "__kmpc_for_static_init_8u");
2341 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2342 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002343 llvm::Type *TypeParams[] = {
2344 getIdentTyPointerTy(), // loc
2345 CGM.Int32Ty, // tid
2346 CGM.Int32Ty, // schedtype
2347 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2348 PtrTy, // p_lower
2349 PtrTy, // p_upper
2350 PtrTy, // p_stride
2351 ITy, // incr
2352 ITy // chunk
2353 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002354 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002355 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2356 return CGM.CreateRuntimeFunction(FnTy, Name);
2357}
2358
Alexander Musman92bdaab2015-03-12 13:37:50 +00002359llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2360 bool IVSigned) {
2361 assert((IVSize == 32 || IVSize == 64) &&
2362 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002363 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002364 IVSize == 32
2365 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2366 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002367 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002368 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2369 CGM.Int32Ty, // tid
2370 CGM.Int32Ty, // schedtype
2371 ITy, // lower
2372 ITy, // upper
2373 ITy, // stride
2374 ITy // chunk
2375 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002376 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002377 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2378 return CGM.CreateRuntimeFunction(FnTy, Name);
2379}
2380
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002381llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2382 bool IVSigned) {
2383 assert((IVSize == 32 || IVSize == 64) &&
2384 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002385 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002386 IVSize == 32
2387 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2388 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2389 llvm::Type *TypeParams[] = {
2390 getIdentTyPointerTy(), // loc
2391 CGM.Int32Ty, // tid
2392 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002393 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002394 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2395 return CGM.CreateRuntimeFunction(FnTy, Name);
2396}
2397
Alexander Musman92bdaab2015-03-12 13:37:50 +00002398llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2399 bool IVSigned) {
2400 assert((IVSize == 32 || IVSize == 64) &&
2401 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002402 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002403 IVSize == 32
2404 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2405 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002406 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2407 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002408 llvm::Type *TypeParams[] = {
2409 getIdentTyPointerTy(), // loc
2410 CGM.Int32Ty, // tid
2411 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2412 PtrTy, // p_lower
2413 PtrTy, // p_upper
2414 PtrTy // p_stride
2415 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002416 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002417 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2418 return CGM.CreateRuntimeFunction(FnTy, Name);
2419}
2420
Alexey Bataev03f270c2018-03-30 18:31:07 +00002421Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2422 if (CGM.getLangOpts().OpenMPSimd)
2423 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002424 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002425 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002426 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2427 SmallString<64> PtrName;
2428 {
2429 llvm::raw_svector_ostream OS(PtrName);
2430 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2431 }
2432 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2433 if (!Ptr) {
2434 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2435 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2436 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002437 if (!CGM.getLangOpts().OpenMPIsDevice) {
2438 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2439 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2440 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2441 }
2442 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2443 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002444 }
2445 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2446 }
2447 return Address::invalid();
2448}
2449
Alexey Bataev97720002014-11-11 04:05:39 +00002450llvm::Constant *
2451CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002452 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2453 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002454 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002455 std::string Suffix = getName({"cache", ""});
2456 return getOrCreateInternalVariable(
2457 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002458}
2459
John McCall7f416cc2015-09-08 08:05:57 +00002460Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2461 const VarDecl *VD,
2462 Address VDAddr,
2463 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002464 if (CGM.getLangOpts().OpenMPUseTLS &&
2465 CGM.getContext().getTargetInfo().isTLSSupported())
2466 return VDAddr;
2467
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002468 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002469 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002470 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2471 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002472 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2473 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002474 return Address(CGF.EmitRuntimeCall(
2475 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2476 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002477}
2478
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002479void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002480 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002481 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2482 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2483 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002484 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002485 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002486 OMPLoc);
2487 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2488 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002489 llvm::Value *Args[] = {
2490 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2491 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002492 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002493 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002494}
2495
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002496llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002497 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002498 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002499 if (CGM.getLangOpts().OpenMPUseTLS &&
2500 CGM.getContext().getTargetInfo().isTLSSupported())
2501 return nullptr;
2502
Alexey Bataev97720002014-11-11 04:05:39 +00002503 VD = VD->getDefinition(CGM.getContext());
2504 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2505 ThreadPrivateWithDefinition.insert(VD);
2506 QualType ASTTy = VD->getType();
2507
2508 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002509 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002510 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2511 // Generate function that re-emits the declaration's initializer into the
2512 // threadprivate copy of the variable VD
2513 CodeGenFunction CtorCGF(CGM);
2514 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002515 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2516 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002517 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002518 Args.push_back(&Dst);
2519
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002520 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002521 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002522 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002523 std::string Name = getName({"__kmpc_global_ctor_", ""});
2524 llvm::Function *Fn =
2525 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002526 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002527 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002528 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002529 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002530 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002531 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002532 Arg = CtorCGF.Builder.CreateElementBitCast(
2533 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002534 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2535 /*IsInitializer=*/true);
2536 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002537 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002538 CGM.getContext().VoidPtrTy, Dst.getLocation());
2539 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2540 CtorCGF.FinishFunction();
2541 Ctor = Fn;
2542 }
2543 if (VD->getType().isDestructedType() != QualType::DK_none) {
2544 // Generate function that emits destructor call for the threadprivate copy
2545 // of the variable VD
2546 CodeGenFunction DtorCGF(CGM);
2547 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002548 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2549 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002550 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002551 Args.push_back(&Dst);
2552
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002553 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002554 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002555 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002556 std::string Name = getName({"__kmpc_global_dtor_", ""});
2557 llvm::Function *Fn =
2558 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002559 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002560 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002561 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002562 // Create a scope with an artificial location for the body of this function.
2563 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002564 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002565 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002566 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2567 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002568 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2569 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2570 DtorCGF.FinishFunction();
2571 Dtor = Fn;
2572 }
2573 // Do not emit init function if it is not required.
2574 if (!Ctor && !Dtor)
2575 return nullptr;
2576
2577 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002578 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2579 /*isVarArg=*/false)
2580 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002581 // Copying constructor for the threadprivate variable.
2582 // Must be NULL - reserved by runtime, but currently it requires that this
2583 // parameter is always NULL. Otherwise it fires assertion.
2584 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2585 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002586 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2587 /*isVarArg=*/false)
2588 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002589 Ctor = llvm::Constant::getNullValue(CtorTy);
2590 }
2591 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002592 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2593 /*isVarArg=*/false)
2594 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002595 Dtor = llvm::Constant::getNullValue(DtorTy);
2596 }
2597 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002598 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002599 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002600 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002601 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002602 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002603 CodeGenFunction InitCGF(CGM);
2604 FunctionArgList ArgList;
2605 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2606 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002607 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002608 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002609 InitCGF.FinishFunction();
2610 return InitFunction;
2611 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002612 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002613 }
2614 return nullptr;
2615}
2616
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002617/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002618/// consists of the file and device IDs as well as line number associated with
2619/// the relevant entry source location.
2620static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2621 unsigned &DeviceID, unsigned &FileID,
2622 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002623 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002624
2625 // The loc should be always valid and have a file ID (the user cannot use
2626 // #pragma directives in macros)
2627
2628 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002629
2630 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2631 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2632
2633 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002634 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2635 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2636 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002637
2638 DeviceID = ID.getDevice();
2639 FileID = ID.getFile();
2640 LineNum = PLoc.getLine();
2641}
2642
2643bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2644 llvm::GlobalVariable *Addr,
2645 bool PerformInit) {
2646 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002647 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002648 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
Alexey Bataevd01b7492018-08-15 19:45:12 +00002649 return CGM.getLangOpts().OpenMPIsDevice;
Alexey Bataev34f8a702018-03-28 14:28:54 +00002650 VD = VD->getDefinition(CGM.getContext());
2651 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2652 return CGM.getLangOpts().OpenMPIsDevice;
2653
2654 QualType ASTTy = VD->getType();
2655
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002656 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002657 // Produce the unique prefix to identify the new target regions. We use
2658 // the source location of the variable declaration which we know to not
2659 // conflict with any target region.
2660 unsigned DeviceID;
2661 unsigned FileID;
2662 unsigned Line;
2663 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2664 SmallString<128> Buffer, Out;
2665 {
2666 llvm::raw_svector_ostream OS(Buffer);
2667 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2668 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2669 }
2670
2671 const Expr *Init = VD->getAnyInitializer();
2672 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2673 llvm::Constant *Ctor;
2674 llvm::Constant *ID;
2675 if (CGM.getLangOpts().OpenMPIsDevice) {
2676 // Generate function that re-emits the declaration's initializer into
2677 // the threadprivate copy of the variable VD
2678 CodeGenFunction CtorCGF(CGM);
2679
2680 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2681 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2682 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2683 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2684 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2685 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2686 FunctionArgList(), Loc, Loc);
2687 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2688 CtorCGF.EmitAnyExprToMem(Init,
2689 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2690 Init->getType().getQualifiers(),
2691 /*IsInitializer=*/true);
2692 CtorCGF.FinishFunction();
2693 Ctor = Fn;
2694 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002695 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002696 } else {
2697 Ctor = new llvm::GlobalVariable(
2698 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2699 llvm::GlobalValue::PrivateLinkage,
2700 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2701 ID = Ctor;
2702 }
2703
2704 // Register the information for the entry associated with the constructor.
2705 Out.clear();
2706 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2707 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002708 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002709 }
2710 if (VD->getType().isDestructedType() != QualType::DK_none) {
2711 llvm::Constant *Dtor;
2712 llvm::Constant *ID;
2713 if (CGM.getLangOpts().OpenMPIsDevice) {
2714 // Generate function that emits destructor call for the threadprivate
2715 // copy of the variable VD
2716 CodeGenFunction DtorCGF(CGM);
2717
2718 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2719 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2720 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2721 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2722 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2723 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2724 FunctionArgList(), Loc, Loc);
2725 // Create a scope with an artificial location for the body of this
2726 // function.
2727 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2728 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2729 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2730 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2731 DtorCGF.FinishFunction();
2732 Dtor = Fn;
2733 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002734 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002735 } else {
2736 Dtor = new llvm::GlobalVariable(
2737 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2738 llvm::GlobalValue::PrivateLinkage,
2739 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2740 ID = Dtor;
2741 }
2742 // Register the information for the entry associated with the destructor.
2743 Out.clear();
2744 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2745 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002746 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002747 }
2748 return CGM.getLangOpts().OpenMPIsDevice;
2749}
2750
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002751Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2752 QualType VarType,
2753 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002754 std::string Suffix = getName({"artificial", ""});
2755 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002756 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002757 llvm::Value *GAddr =
2758 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002759 llvm::Value *Args[] = {
2760 emitUpdateLocation(CGF, SourceLocation()),
2761 getThreadID(CGF, SourceLocation()),
2762 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2763 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2764 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002765 getOrCreateInternalVariable(
2766 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002767 return Address(
2768 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2769 CGF.EmitRuntimeCall(
2770 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2771 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2772 CGM.getPointerAlign());
2773}
2774
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002775void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2776 const RegionCodeGenTy &ThenGen,
2777 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002778 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2779
2780 // If the condition constant folds and can be elided, try to avoid emitting
2781 // the condition and the dead arm of the if/else.
2782 bool CondConstant;
2783 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002784 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002785 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002786 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002787 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002788 return;
2789 }
2790
2791 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2792 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002793 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2794 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2795 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002796 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2797
2798 // Emit the 'then' code.
2799 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002800 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002801 CGF.EmitBranch(ContBlock);
2802 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002803 // There is no need to emit line number for unconditional branch.
2804 (void)ApplyDebugLocation::CreateEmpty(CGF);
2805 CGF.EmitBlock(ElseBlock);
2806 ElseGen(CGF);
2807 // There is no need to emit line number for unconditional branch.
2808 (void)ApplyDebugLocation::CreateEmpty(CGF);
2809 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002810 // Emit the continuation block for code after the if.
2811 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002812}
2813
Alexey Bataev1d677132015-04-22 13:57:31 +00002814void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2815 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002816 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002817 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002818 if (!CGF.HaveInsertPoint())
2819 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002820 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002821 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2822 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002823 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002824 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002825 llvm::Value *Args[] = {
2826 RTLoc,
2827 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002828 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002829 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2830 RealArgs.append(std::begin(Args), std::end(Args));
2831 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2832
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002833 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002834 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2835 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002836 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2837 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002838 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2839 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002840 // Build calls:
2841 // __kmpc_serialized_parallel(&Loc, GTid);
2842 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002843 CGF.EmitRuntimeCall(
2844 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002845
Alexey Bataev1d677132015-04-22 13:57:31 +00002846 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002847 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2848 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002849 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002850 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataev8521ff62018-07-25 20:03:01 +00002851 // ThreadId for serialized parallels is 0.
2852 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002853 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2854 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002855 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002856
Alexey Bataev1d677132015-04-22 13:57:31 +00002857 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002858 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002859 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002860 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2861 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002862 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002863 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002864 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002865 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002866 RegionCodeGenTy ThenRCG(ThenGen);
2867 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002868 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002869}
2870
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002871// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002872// thread-ID variable (it is passed in a first argument of the outlined function
2873// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2874// regular serial code region, get thread ID by calling kmp_int32
2875// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2876// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002877Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2878 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002879 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002880 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002881 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002882 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002883
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002884 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2885 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002886 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002887 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002888 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002889 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002890
2891 return ThreadIDTemp;
2892}
2893
Alexey Bataev97720002014-11-11 04:05:39 +00002894llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002895CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002896 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002897 SmallString<256> Buffer;
2898 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002899 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002900 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002901 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002902 if (Elem.second) {
2903 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002904 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002905 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002906 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002907
David Blaikie13156b62014-11-19 03:06:06 +00002908 return Elem.second = new llvm::GlobalVariable(
2909 CGM.getModule(), Ty, /*IsConstant*/ false,
2910 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2911 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002912}
2913
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002914llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002915 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2916 std::string Name = getName({Prefix, "var"});
2917 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002918}
2919
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002920namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002921/// Common pre(post)-action for different OpenMP constructs.
2922class CommonActionTy final : public PrePostActionTy {
2923 llvm::Value *EnterCallee;
2924 ArrayRef<llvm::Value *> EnterArgs;
2925 llvm::Value *ExitCallee;
2926 ArrayRef<llvm::Value *> ExitArgs;
2927 bool Conditional;
2928 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002929
2930public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002931 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2932 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2933 bool Conditional = false)
2934 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2935 ExitArgs(ExitArgs), Conditional(Conditional) {}
2936 void Enter(CodeGenFunction &CGF) override {
2937 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2938 if (Conditional) {
2939 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2940 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2941 ContBlock = CGF.createBasicBlock("omp_if.end");
2942 // Generate the branch (If-stmt)
2943 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2944 CGF.EmitBlock(ThenBlock);
2945 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002946 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002947 void Done(CodeGenFunction &CGF) {
2948 // Emit the rest of blocks/branches
2949 CGF.EmitBranch(ContBlock);
2950 CGF.EmitBlock(ContBlock, true);
2951 }
2952 void Exit(CodeGenFunction &CGF) override {
2953 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002954 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002955};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002956} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002957
2958void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2959 StringRef CriticalName,
2960 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002961 SourceLocation Loc, const Expr *Hint) {
2962 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002963 // CriticalOpGen();
2964 // __kmpc_end_critical(ident_t *, gtid, Lock);
2965 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002966 if (!CGF.HaveInsertPoint())
2967 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002968 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2969 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002970 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2971 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002972 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002973 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2974 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2975 }
2976 CommonActionTy Action(
2977 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2978 : OMPRTL__kmpc_critical),
2979 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2980 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002981 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002982}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002983
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002984void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002985 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002986 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002987 if (!CGF.HaveInsertPoint())
2988 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002989 // if(__kmpc_master(ident_t *, gtid)) {
2990 // MasterOpGen();
2991 // __kmpc_end_master(ident_t *, gtid);
2992 // }
2993 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002994 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002995 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2996 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2997 /*Conditional=*/true);
2998 MasterOpGen.setAction(Action);
2999 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
3000 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00003001}
3002
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003003void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
3004 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003005 if (!CGF.HaveInsertPoint())
3006 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003007 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3008 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003009 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003010 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003011 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003012 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3013 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003014}
3015
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003016void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3017 const RegionCodeGenTy &TaskgroupOpGen,
3018 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003019 if (!CGF.HaveInsertPoint())
3020 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003021 // __kmpc_taskgroup(ident_t *, gtid);
3022 // TaskgroupOpGen();
3023 // __kmpc_end_taskgroup(ident_t *, gtid);
3024 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003025 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3026 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3027 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3028 Args);
3029 TaskgroupOpGen.setAction(Action);
3030 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003031}
3032
John McCall7f416cc2015-09-08 08:05:57 +00003033/// Given an array of pointers to variables, project the address of a
3034/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003035static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3036 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003037 // Pull out the pointer to the variable.
3038 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003039 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003040 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3041
3042 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003043 Addr = CGF.Builder.CreateElementBitCast(
3044 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003045 return Addr;
3046}
3047
Alexey Bataeva63048e2015-03-23 06:18:07 +00003048static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003049 CodeGenModule &CGM, llvm::Type *ArgsType,
3050 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003051 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3052 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003053 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003054 // void copy_func(void *LHSArg, void *RHSArg);
3055 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003056 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3057 ImplicitParamDecl::Other);
3058 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3059 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003060 Args.push_back(&LHSArg);
3061 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003062 const auto &CGFI =
3063 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003064 std::string Name =
3065 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3066 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3067 llvm::GlobalValue::InternalLinkage, Name,
3068 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003069 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003070 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003071 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003072 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003073 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003074 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003075 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3076 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3077 ArgsType), CGF.getPointerAlign());
3078 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3079 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3080 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003081 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3082 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3083 // ...
3084 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003085 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003086 const auto *DestVar =
3087 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003088 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3089
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003090 const auto *SrcVar =
3091 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003092 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3093
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003094 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003095 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003096 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003097 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003098 CGF.FinishFunction();
3099 return Fn;
3100}
3101
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003102void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003103 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003104 SourceLocation Loc,
3105 ArrayRef<const Expr *> CopyprivateVars,
3106 ArrayRef<const Expr *> SrcExprs,
3107 ArrayRef<const Expr *> DstExprs,
3108 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003109 if (!CGF.HaveInsertPoint())
3110 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003111 assert(CopyprivateVars.size() == SrcExprs.size() &&
3112 CopyprivateVars.size() == DstExprs.size() &&
3113 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003114 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003115 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003116 // if(__kmpc_single(ident_t *, gtid)) {
3117 // SingleOpGen();
3118 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003119 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003120 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003121 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3122 // <copy_func>, did_it);
3123
John McCall7f416cc2015-09-08 08:05:57 +00003124 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003125 if (!CopyprivateVars.empty()) {
3126 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003127 QualType KmpInt32Ty =
3128 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003129 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003130 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003131 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003132 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003133 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003134 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3135 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3136 /*Conditional=*/true);
3137 SingleOpGen.setAction(Action);
3138 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3139 if (DidIt.isValid()) {
3140 // did_it = 1;
3141 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3142 }
3143 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003144 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3145 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003146 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003147 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003148 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003149 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3150 /*IndexTypeQuals=*/0);
3151 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003152 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003153 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3154 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003155 Address Elem = CGF.Builder.CreateConstArrayGEP(
3156 CopyprivateList, I, CGF.getPointerSize());
3157 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003158 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003159 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3160 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003161 }
3162 // Build function that copies private values from single region to all other
3163 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003164 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003165 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003166 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003167 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003168 Address CL =
3169 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3170 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003171 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003172 llvm::Value *Args[] = {
3173 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3174 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003175 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003176 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003177 CpyFn, // void (*) (void *, void *) <copy_func>
3178 DidItVal // i32 did_it
3179 };
3180 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3181 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003182}
3183
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003184void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3185 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003186 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003187 if (!CGF.HaveInsertPoint())
3188 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003189 // __kmpc_ordered(ident_t *, gtid);
3190 // OrderedOpGen();
3191 // __kmpc_end_ordered(ident_t *, gtid);
3192 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003193 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003194 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003195 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3196 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3197 Args);
3198 OrderedOpGen.setAction(Action);
3199 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3200 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003201 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003202 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003203}
3204
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003205void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003206 OpenMPDirectiveKind Kind, bool EmitChecks,
3207 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003208 if (!CGF.HaveInsertPoint())
3209 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003210 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003211 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003212 unsigned Flags;
3213 if (Kind == OMPD_for)
3214 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3215 else if (Kind == OMPD_sections)
3216 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3217 else if (Kind == OMPD_single)
3218 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3219 else if (Kind == OMPD_barrier)
3220 Flags = OMP_IDENT_BARRIER_EXPL;
3221 else
3222 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003223 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3224 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003225 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3226 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003227 if (auto *OMPRegionInfo =
3228 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003229 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003230 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003231 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003232 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003233 // if (__kmpc_cancel_barrier()) {
3234 // exit from construct;
3235 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003236 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3237 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3238 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003239 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3240 CGF.EmitBlock(ExitBB);
3241 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003242 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003243 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003244 CGF.EmitBranchThroughCleanup(CancelDestination);
3245 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3246 }
3247 return;
3248 }
3249 }
3250 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003251}
3252
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003253/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003254static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003255 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003256 switch (ScheduleKind) {
3257 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003258 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3259 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003260 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003261 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003262 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003263 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003264 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003265 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3266 case OMPC_SCHEDULE_auto:
3267 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003268 case OMPC_SCHEDULE_unknown:
3269 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003270 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003271 }
3272 llvm_unreachable("Unexpected runtime schedule");
3273}
3274
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003275/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003276static OpenMPSchedType
3277getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3278 // only static is allowed for dist_schedule
3279 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3280}
3281
Alexander Musmanc6388682014-12-15 07:07:06 +00003282bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3283 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003284 OpenMPSchedType Schedule =
3285 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003286 return Schedule == OMP_sch_static;
3287}
3288
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003289bool CGOpenMPRuntime::isStaticNonchunked(
3290 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003291 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003292 return Schedule == OMP_dist_sch_static;
3293}
3294
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003295bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
3296 bool Chunked) const {
3297 OpenMPSchedType Schedule =
3298 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3299 return Schedule == OMP_sch_static_chunked;
3300}
3301
3302bool CGOpenMPRuntime::isStaticChunked(
3303 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3304 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3305 return Schedule == OMP_dist_sch_static_chunked;
3306}
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003307
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003308bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003309 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003310 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003311 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3312 return Schedule != OMP_sch_static;
3313}
3314
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003315static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3316 OpenMPScheduleClauseModifier M1,
3317 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003318 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003319 switch (M1) {
3320 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003321 Modifier = OMP_sch_modifier_monotonic;
3322 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003323 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003324 Modifier = OMP_sch_modifier_nonmonotonic;
3325 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003326 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003327 if (Schedule == OMP_sch_static_chunked)
3328 Schedule = OMP_sch_static_balanced_chunked;
3329 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003330 case OMPC_SCHEDULE_MODIFIER_last:
3331 case OMPC_SCHEDULE_MODIFIER_unknown:
3332 break;
3333 }
3334 switch (M2) {
3335 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003336 Modifier = OMP_sch_modifier_monotonic;
3337 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003338 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003339 Modifier = OMP_sch_modifier_nonmonotonic;
3340 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003341 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003342 if (Schedule == OMP_sch_static_chunked)
3343 Schedule = OMP_sch_static_balanced_chunked;
3344 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003345 case OMPC_SCHEDULE_MODIFIER_last:
3346 case OMPC_SCHEDULE_MODIFIER_unknown:
3347 break;
3348 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003349 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003350}
3351
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003352void CGOpenMPRuntime::emitForDispatchInit(
3353 CodeGenFunction &CGF, SourceLocation Loc,
3354 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3355 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003356 if (!CGF.HaveInsertPoint())
3357 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003358 OpenMPSchedType Schedule = getRuntimeSchedule(
3359 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003360 assert(Ordered ||
3361 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003362 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3363 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003364 // Call __kmpc_dispatch_init(
3365 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3366 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3367 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003368
John McCall7f416cc2015-09-08 08:05:57 +00003369 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003370 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3371 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003372 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003373 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3374 CGF.Builder.getInt32(addMonoNonMonoModifier(
3375 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003376 DispatchValues.LB, // Lower
3377 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003378 CGF.Builder.getIntN(IVSize, 1), // Stride
3379 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003380 };
3381 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3382}
3383
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003384static void emitForStaticInitCall(
3385 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3386 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3387 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003388 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003389 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003390 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003391
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003392 assert(!Values.Ordered);
3393 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3394 Schedule == OMP_sch_static_balanced_chunked ||
3395 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3396 Schedule == OMP_dist_sch_static ||
3397 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003398
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003399 // Call __kmpc_for_static_init(
3400 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3401 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3402 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3403 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3404 llvm::Value *Chunk = Values.Chunk;
3405 if (Chunk == nullptr) {
3406 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3407 Schedule == OMP_dist_sch_static) &&
3408 "expected static non-chunked schedule");
3409 // If the Chunk was not specified in the clause - use default value 1.
3410 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3411 } else {
3412 assert((Schedule == OMP_sch_static_chunked ||
3413 Schedule == OMP_sch_static_balanced_chunked ||
3414 Schedule == OMP_ord_static_chunked ||
3415 Schedule == OMP_dist_sch_static_chunked) &&
3416 "expected static chunked schedule");
3417 }
3418 llvm::Value *Args[] = {
3419 UpdateLocation,
3420 ThreadId,
3421 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3422 M2)), // Schedule type
3423 Values.IL.getPointer(), // &isLastIter
3424 Values.LB.getPointer(), // &LB
3425 Values.UB.getPointer(), // &UB
3426 Values.ST.getPointer(), // &Stride
3427 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3428 Chunk // Chunk
3429 };
3430 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003431}
3432
John McCall7f416cc2015-09-08 08:05:57 +00003433void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3434 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003435 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003436 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003437 const StaticRTInput &Values) {
3438 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3439 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3440 assert(isOpenMPWorksharingDirective(DKind) &&
3441 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003442 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003443 isOpenMPLoopDirective(DKind)
3444 ? OMP_IDENT_WORK_LOOP
3445 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003446 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3447 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003448 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003449 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003450 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003451}
John McCall7f416cc2015-09-08 08:05:57 +00003452
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003453void CGOpenMPRuntime::emitDistributeStaticInit(
3454 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003455 OpenMPDistScheduleClauseKind SchedKind,
3456 const CGOpenMPRuntime::StaticRTInput &Values) {
3457 OpenMPSchedType ScheduleNum =
3458 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003459 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003460 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003461 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3462 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003463 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003464 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3465 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003466 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003467}
3468
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003469void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003470 SourceLocation Loc,
3471 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003472 if (!CGF.HaveInsertPoint())
3473 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003474 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003475 llvm::Value *Args[] = {
3476 emitUpdateLocation(CGF, Loc,
3477 isOpenMPDistributeDirective(DKind)
3478 ? OMP_IDENT_WORK_DISTRIBUTE
3479 : isOpenMPLoopDirective(DKind)
3480 ? OMP_IDENT_WORK_LOOP
3481 : OMP_IDENT_WORK_SECTIONS),
3482 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003483 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3484 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003485}
3486
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003487void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3488 SourceLocation Loc,
3489 unsigned IVSize,
3490 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003491 if (!CGF.HaveInsertPoint())
3492 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003493 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003494 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003495 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3496}
3497
Alexander Musman92bdaab2015-03-12 13:37:50 +00003498llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3499 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003500 bool IVSigned, Address IL,
3501 Address LB, Address UB,
3502 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003503 // Call __kmpc_dispatch_next(
3504 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3505 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3506 // kmp_int[32|64] *p_stride);
3507 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003508 emitUpdateLocation(CGF, Loc),
3509 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003510 IL.getPointer(), // &isLastIter
3511 LB.getPointer(), // &Lower
3512 UB.getPointer(), // &Upper
3513 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003514 };
3515 llvm::Value *Call =
3516 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3517 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003518 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003519 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003520}
3521
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003522void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3523 llvm::Value *NumThreads,
3524 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003525 if (!CGF.HaveInsertPoint())
3526 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003527 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3528 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003529 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003530 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003531 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3532 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003533}
3534
Alexey Bataev7f210c62015-06-18 13:40:03 +00003535void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3536 OpenMPProcBindClauseKind ProcBind,
3537 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003538 if (!CGF.HaveInsertPoint())
3539 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003540 // Constants for proc bind value accepted by the runtime.
3541 enum ProcBindTy {
3542 ProcBindFalse = 0,
3543 ProcBindTrue,
3544 ProcBindMaster,
3545 ProcBindClose,
3546 ProcBindSpread,
3547 ProcBindIntel,
3548 ProcBindDefault
3549 } RuntimeProcBind;
3550 switch (ProcBind) {
3551 case OMPC_PROC_BIND_master:
3552 RuntimeProcBind = ProcBindMaster;
3553 break;
3554 case OMPC_PROC_BIND_close:
3555 RuntimeProcBind = ProcBindClose;
3556 break;
3557 case OMPC_PROC_BIND_spread:
3558 RuntimeProcBind = ProcBindSpread;
3559 break;
3560 case OMPC_PROC_BIND_unknown:
3561 llvm_unreachable("Unsupported proc_bind value.");
3562 }
3563 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3564 llvm::Value *Args[] = {
3565 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3566 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3567 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3568}
3569
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003570void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3571 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003572 if (!CGF.HaveInsertPoint())
3573 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003574 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003575 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3576 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003577}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003578
Alexey Bataev62b63b12015-03-10 07:28:44 +00003579namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003580/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003581enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003582 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003583 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003584 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003585 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003586 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003587 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003588 /// Function with call of destructors for private variables.
3589 Data1,
3590 /// Task priority.
3591 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003592 /// (Taskloops only) Lower bound.
3593 KmpTaskTLowerBound,
3594 /// (Taskloops only) Upper bound.
3595 KmpTaskTUpperBound,
3596 /// (Taskloops only) Stride.
3597 KmpTaskTStride,
3598 /// (Taskloops only) Is last iteration flag.
3599 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003600 /// (Taskloops only) Reduction data.
3601 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003602};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003603} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003604
Samuel Antaoee8fb302016-01-06 13:42:12 +00003605bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003606 return OffloadEntriesTargetRegion.empty() &&
3607 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003608}
3609
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003610/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003611void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3612 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3613 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003614 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003615 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3616 "only required for the device "
3617 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003618 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003619 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003620 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003621 ++OffloadingEntriesNum;
3622}
3623
3624void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3625 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3626 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003627 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003628 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003629 // If we are emitting code for a target, the entry is already initialized,
3630 // only has to be registered.
3631 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003632 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3633 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3634 DiagnosticsEngine::Error,
3635 "Unable to find target region on line '%0' in the device code.");
3636 CGM.getDiags().Report(DiagID) << LineNum;
3637 return;
3638 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003639 auto &Entry =
3640 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003641 assert(Entry.isValid() && "Entry not initialized!");
3642 Entry.setAddress(Addr);
3643 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003644 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003645 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003646 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003647 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003648 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003649 }
3650}
3651
3652bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003653 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3654 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003655 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3656 if (PerDevice == OffloadEntriesTargetRegion.end())
3657 return false;
3658 auto PerFile = PerDevice->second.find(FileID);
3659 if (PerFile == PerDevice->second.end())
3660 return false;
3661 auto PerParentName = PerFile->second.find(ParentName);
3662 if (PerParentName == PerFile->second.end())
3663 return false;
3664 auto PerLine = PerParentName->second.find(LineNum);
3665 if (PerLine == PerParentName->second.end())
3666 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003667 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003668 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003669 return false;
3670 return true;
3671}
3672
3673void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3674 const OffloadTargetRegionEntryInfoActTy &Action) {
3675 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003676 for (const auto &D : OffloadEntriesTargetRegion)
3677 for (const auto &F : D.second)
3678 for (const auto &P : F.second)
3679 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003680 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003681}
3682
Alexey Bataev03f270c2018-03-30 18:31:07 +00003683void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3684 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3685 OMPTargetGlobalVarEntryKind Flags,
3686 unsigned Order) {
3687 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3688 "only required for the device "
3689 "code generation.");
3690 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3691 ++OffloadingEntriesNum;
3692}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003693
Alexey Bataev03f270c2018-03-30 18:31:07 +00003694void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3695 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3696 CharUnits VarSize,
3697 OMPTargetGlobalVarEntryKind Flags,
3698 llvm::GlobalValue::LinkageTypes Linkage) {
3699 if (CGM.getLangOpts().OpenMPIsDevice) {
3700 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3701 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3702 "Entry not initialized!");
3703 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3704 "Resetting with the new address.");
3705 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3706 return;
3707 Entry.setAddress(Addr);
3708 Entry.setVarSize(VarSize);
3709 Entry.setLinkage(Linkage);
3710 } else {
3711 if (hasDeviceGlobalVarEntryInfo(VarName))
3712 return;
3713 OffloadEntriesDeviceGlobalVar.try_emplace(
3714 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3715 ++OffloadingEntriesNum;
3716 }
3717}
3718
3719void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3720 actOnDeviceGlobalVarEntriesInfo(
3721 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3722 // Scan all target region entries and perform the provided action.
3723 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3724 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003725}
3726
3727llvm::Function *
3728CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003729 // If we don't have entries or if we are emitting code for the device, we
3730 // don't need to do anything.
3731 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3732 return nullptr;
3733
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003734 llvm::Module &M = CGM.getModule();
3735 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003736
3737 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003738 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003739
3740 // We should be creating an offloading descriptor only if there are devices
3741 // specified.
3742 assert(!Devices.empty() && "No OpenMP offloading devices??");
3743
3744 // Create the external variables that will point to the begin and end of the
3745 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003746 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003747 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003748 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003749 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003750 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003751 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003752 EntriesBeginName);
3753 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3754 auto *HostEntriesEnd =
3755 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3756 llvm::GlobalValue::ExternalLinkage,
3757 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003758
3759 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003760 auto *DeviceImageTy = cast<llvm::StructType>(
3761 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003762 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003763 ConstantArrayBuilder DeviceImagesEntries =
3764 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003765
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003766 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003767 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003768 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003769 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003770 M, CGM.Int8Ty, /*isConstant=*/true,
3771 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003772 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3773 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003774 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003775 M, CGM.Int8Ty, /*isConstant=*/true,
3776 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003777 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003778
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003779 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3780 HostEntriesEnd};
3781 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3782 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003783 }
3784
3785 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003786 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003787 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003788 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3789 CGM.getPointerAlign(),
3790 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003791 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003792
3793 // This is a Zero array to be used in the creation of the constant expressions
3794 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3795 llvm::Constant::getNullValue(CGM.Int32Ty)};
3796
3797 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003798 llvm::Constant *Data[] = {
3799 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3800 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3801 DeviceImages, Index),
3802 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003803 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003804 llvm::GlobalVariable *Desc = createGlobalStruct(
3805 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003806
3807 // Emit code to register or unregister the descriptor at execution
3808 // startup or closing, respectively.
3809
Alexey Bataev03f270c2018-03-30 18:31:07 +00003810 llvm::Function *UnRegFn;
3811 {
3812 FunctionArgList Args;
3813 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3814 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003815
Alexey Bataev03f270c2018-03-30 18:31:07 +00003816 CodeGenFunction CGF(CGM);
3817 // Disable debug info for global (de-)initializer because they are not part
3818 // of some particular construct.
3819 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003820 const auto &FI =
3821 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3822 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003823 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3824 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003825 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3826 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3827 Desc);
3828 CGF.FinishFunction();
3829 }
3830 llvm::Function *RegFn;
3831 {
3832 CodeGenFunction CGF(CGM);
3833 // Disable debug info for global (de-)initializer because they are not part
3834 // of some particular construct.
3835 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003836 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003837 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003838
3839 // Encode offload target triples into the registration function name. It
3840 // will serve as a comdat key for the registration/unregistration code for
3841 // this particular combination of offloading targets.
3842 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3843 RegFnNameParts[0] = "omp_offloading";
3844 RegFnNameParts[1] = "descriptor_reg";
3845 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3846 [](const llvm::Triple &T) -> const std::string& {
3847 return T.getTriple();
3848 });
3849 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3850 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003851 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003852 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3853 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3854 // Create a variable to drive the registration and unregistration of the
3855 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3856 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3857 SourceLocation(), nullptr, C.CharTy,
3858 ImplicitParamDecl::Other);
3859 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3860 CGF.FinishFunction();
3861 }
George Rokos29d0f002017-05-27 03:03:13 +00003862 if (CGM.supportsCOMDAT()) {
3863 // It is sufficient to call registration function only once, so create a
3864 // COMDAT group for registration/unregistration functions and associated
3865 // data. That would reduce startup time and code size. Registration
3866 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003867 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003868 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3869 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3870 RegFn->setComdat(ComdatKey);
3871 UnRegFn->setComdat(ComdatKey);
3872 DeviceImages->setComdat(ComdatKey);
3873 Desc->setComdat(ComdatKey);
3874 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003875 return RegFn;
3876}
3877
Alexey Bataev03f270c2018-03-30 18:31:07 +00003878void CGOpenMPRuntime::createOffloadEntry(
3879 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3880 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003881 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003882 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003883 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003884
3885 // Create constant string with the name.
3886 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3887
Alexey Bataev18fa2322018-05-02 14:20:50 +00003888 std::string StringName = getName({"omp_offloading", "entry_name"});
3889 auto *Str = new llvm::GlobalVariable(
3890 M, StrPtrInit->getType(), /*isConstant=*/true,
3891 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003892 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003893
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003894 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3895 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3896 llvm::ConstantInt::get(CGM.SizeTy, Size),
3897 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3898 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003899 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003900 llvm::GlobalVariable *Entry = createGlobalStruct(
3901 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3902 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003903
3904 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003905 std::string Section = getName({"omp_offloading", "entries"});
3906 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003907}
3908
3909void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3910 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003911 // can easily figure out what to emit. The produced metadata looks like
3912 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003913 //
3914 // !omp_offload.info = !{!1, ...}
3915 //
3916 // Right now we only generate metadata for function that contain target
3917 // regions.
3918
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003919 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003920 if (OffloadEntriesInfoManager.empty())
3921 return;
3922
3923 llvm::Module &M = CGM.getModule();
3924 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003925 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003926 OrderedEntries(OffloadEntriesInfoManager.size());
3927
Simon Pilgrim2c518802017-03-30 14:13:19 +00003928 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003929 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003930 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003931 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003932 };
3933
Alexey Bataev03f270c2018-03-30 18:31:07 +00003934 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3935
3936 // Create the offloading info metadata node.
3937 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003938
3939 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003940 auto &&TargetRegionMetadataEmitter =
3941 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3942 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3943 unsigned Line,
3944 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3945 // Generate metadata for target regions. Each entry of this metadata
3946 // contains:
3947 // - Entry 0 -> Kind of this type of metadata (0).
3948 // - Entry 1 -> Device ID of the file where the entry was identified.
3949 // - Entry 2 -> File ID of the file where the entry was identified.
3950 // - Entry 3 -> Mangled name of the function where the entry was
3951 // identified.
3952 // - Entry 4 -> Line in the file where the entry was identified.
3953 // - Entry 5 -> Order the entry was created.
3954 // The first element of the metadata node is the kind.
3955 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3956 GetMDInt(FileID), GetMDString(ParentName),
3957 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003958
Alexey Bataev03f270c2018-03-30 18:31:07 +00003959 // Save this entry in the right position of the ordered entries array.
3960 OrderedEntries[E.getOrder()] = &E;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003961
Alexey Bataev03f270c2018-03-30 18:31:07 +00003962 // Add metadata to the named metadata node.
3963 MD->addOperand(llvm::MDNode::get(C, Ops));
3964 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003965
3966 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3967 TargetRegionMetadataEmitter);
3968
Alexey Bataev03f270c2018-03-30 18:31:07 +00003969 // Create function that emits metadata for each device global variable entry;
3970 auto &&DeviceGlobalVarMetadataEmitter =
3971 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3972 MD](StringRef MangledName,
3973 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3974 &E) {
3975 // Generate metadata for global variables. Each entry of this metadata
3976 // contains:
3977 // - Entry 0 -> Kind of this type of metadata (1).
3978 // - Entry 1 -> Mangled name of the variable.
3979 // - Entry 2 -> Declare target kind.
3980 // - Entry 3 -> Order the entry was created.
3981 // The first element of the metadata node is the kind.
3982 llvm::Metadata *Ops[] = {
3983 GetMDInt(E.getKind()), GetMDString(MangledName),
3984 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3985
3986 // Save this entry in the right position of the ordered entries array.
3987 OrderedEntries[E.getOrder()] = &E;
3988
3989 // Add metadata to the named metadata node.
3990 MD->addOperand(llvm::MDNode::get(C, Ops));
3991 };
3992
3993 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3994 DeviceGlobalVarMetadataEmitter);
3995
3996 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003997 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003998 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003999 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
4000 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004001 if (!CE->getID() || !CE->getAddress()) {
4002 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4003 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00004004 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004005 "address or the ID is invalid.");
4006 CGM.getDiags().Report(DiagID);
4007 continue;
4008 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00004009 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004010 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
4011 } else if (const auto *CE =
4012 dyn_cast<OffloadEntriesInfoManagerTy::
4013 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004014 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
4015 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4016 CE->getFlags());
4017 switch (Flags) {
4018 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
4019 if (!CE->getAddress()) {
4020 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4021 DiagnosticsEngine::Error,
4022 "Offloading entry for declare target variable is incorrect: the "
4023 "address is invalid.");
4024 CGM.getDiags().Report(DiagID);
4025 continue;
4026 }
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00004027 // The vaiable has no definition - no need to add the entry.
4028 if (CE->getVarSize().isZero())
4029 continue;
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004030 break;
4031 }
4032 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
4033 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4034 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4035 "Declaret target link address is set.");
4036 if (CGM.getLangOpts().OpenMPIsDevice)
4037 continue;
4038 if (!CE->getAddress()) {
4039 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4040 DiagnosticsEngine::Error,
4041 "Offloading entry for declare target variable is incorrect: the "
4042 "address is invalid.");
4043 CGM.getDiags().Report(DiagID);
4044 continue;
4045 }
4046 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004047 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004048 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004049 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004050 CE->getLinkage());
4051 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004052 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004053 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004054 }
4055}
4056
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004057/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004058/// metadata.
4059void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4060 // If we are in target mode, load the metadata from the host IR. This code has
4061 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4062
4063 if (!CGM.getLangOpts().OpenMPIsDevice)
4064 return;
4065
4066 if (CGM.getLangOpts().OMPHostIRFile.empty())
4067 return;
4068
4069 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004070 if (auto EC = Buf.getError()) {
4071 CGM.getDiags().Report(diag::err_cannot_open_file)
4072 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004073 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004074 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004075
4076 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004077 auto ME = expectedToErrorOrAndEmitErrors(
4078 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004079
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004080 if (auto EC = ME.getError()) {
4081 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4082 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4083 CGM.getDiags().Report(DiagID)
4084 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004085 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004086 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004087
4088 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4089 if (!MD)
4090 return;
4091
George Burgess IV00f70bd2018-03-01 05:43:23 +00004092 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004093 auto &&GetMDInt = [MN](unsigned Idx) {
4094 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004095 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4096 };
4097
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004098 auto &&GetMDString = [MN](unsigned Idx) {
4099 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004100 return V->getString();
4101 };
4102
Alexey Bataev03f270c2018-03-30 18:31:07 +00004103 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004104 default:
4105 llvm_unreachable("Unexpected metadata!");
4106 break;
4107 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004108 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004109 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004110 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4111 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4112 /*Order=*/GetMDInt(5));
4113 break;
4114 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4115 OffloadingEntryInfoDeviceGlobalVar:
4116 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4117 /*MangledName=*/GetMDString(1),
4118 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4119 /*Flags=*/GetMDInt(2)),
4120 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004121 break;
4122 }
4123 }
4124}
4125
Alexey Bataev62b63b12015-03-10 07:28:44 +00004126void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4127 if (!KmpRoutineEntryPtrTy) {
4128 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004129 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004130 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4131 FunctionProtoType::ExtProtoInfo EPI;
4132 KmpRoutineEntryPtrQTy = C.getPointerType(
4133 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4134 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4135 }
4136}
4137
Samuel Antaoee8fb302016-01-06 13:42:12 +00004138QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004139 // Make sure the type of the entry is already created. This is the type we
4140 // have to create:
4141 // struct __tgt_offload_entry{
4142 // void *addr; // Pointer to the offload entry info.
4143 // // (function or global)
4144 // char *name; // Name of the function or global.
4145 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004146 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4147 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004148 // };
4149 if (TgtOffloadEntryQTy.isNull()) {
4150 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004151 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004152 RD->startDefinition();
4153 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4154 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4155 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004156 addFieldToRecordDecl(
4157 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4158 addFieldToRecordDecl(
4159 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004160 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004161 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004162 TgtOffloadEntryQTy = C.getRecordType(RD);
4163 }
4164 return TgtOffloadEntryQTy;
4165}
4166
4167QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4168 // These are the types we need to build:
4169 // struct __tgt_device_image{
4170 // void *ImageStart; // Pointer to the target code start.
4171 // void *ImageEnd; // Pointer to the target code end.
4172 // // We also add the host entries to the device image, as it may be useful
4173 // // for the target runtime to have access to that information.
4174 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4175 // // the entries.
4176 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4177 // // entries (non inclusive).
4178 // };
4179 if (TgtDeviceImageQTy.isNull()) {
4180 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004181 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004182 RD->startDefinition();
4183 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4184 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4185 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4186 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4187 RD->completeDefinition();
4188 TgtDeviceImageQTy = C.getRecordType(RD);
4189 }
4190 return TgtDeviceImageQTy;
4191}
4192
4193QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4194 // struct __tgt_bin_desc{
4195 // int32_t NumDevices; // Number of devices supported.
4196 // __tgt_device_image *DeviceImages; // Arrays of device images
4197 // // (one per device).
4198 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4199 // // entries.
4200 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4201 // // entries (non inclusive).
4202 // };
4203 if (TgtBinaryDescriptorQTy.isNull()) {
4204 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004205 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004206 RD->startDefinition();
4207 addFieldToRecordDecl(
4208 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4209 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4210 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4211 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4212 RD->completeDefinition();
4213 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4214 }
4215 return TgtBinaryDescriptorQTy;
4216}
4217
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004218namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004219struct PrivateHelpersTy {
4220 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4221 const VarDecl *PrivateElemInit)
4222 : Original(Original), PrivateCopy(PrivateCopy),
4223 PrivateElemInit(PrivateElemInit) {}
4224 const VarDecl *Original;
4225 const VarDecl *PrivateCopy;
4226 const VarDecl *PrivateElemInit;
4227};
4228typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004229} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004230
Alexey Bataev9e034042015-05-05 04:05:12 +00004231static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004232createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004233 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004234 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004235 // Build struct .kmp_privates_t. {
4236 // /* private vars */
4237 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004238 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004239 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004240 for (const auto &Pair : Privates) {
4241 const VarDecl *VD = Pair.second.Original;
4242 QualType Type = VD->getType().getNonReferenceType();
4243 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004244 if (VD->hasAttrs()) {
4245 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4246 E(VD->getAttrs().end());
4247 I != E; ++I)
4248 FD->addAttr(*I);
4249 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004250 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004251 RD->completeDefinition();
4252 return RD;
4253 }
4254 return nullptr;
4255}
4256
Alexey Bataev9e034042015-05-05 04:05:12 +00004257static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004258createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4259 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004260 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004261 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004262 // Build struct kmp_task_t {
4263 // void * shareds;
4264 // kmp_routine_entry_t routine;
4265 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004266 // kmp_cmplrdata_t data1;
4267 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004268 // For taskloops additional fields:
4269 // kmp_uint64 lb;
4270 // kmp_uint64 ub;
4271 // kmp_int64 st;
4272 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004273 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004274 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004275 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004276 UD->startDefinition();
4277 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4278 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4279 UD->completeDefinition();
4280 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004281 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004282 RD->startDefinition();
4283 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4284 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4285 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004286 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4287 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004288 if (isOpenMPTaskLoopDirective(Kind)) {
4289 QualType KmpUInt64Ty =
4290 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4291 QualType KmpInt64Ty =
4292 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4293 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4294 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4295 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4296 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004297 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004298 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004299 RD->completeDefinition();
4300 return RD;
4301}
4302
4303static RecordDecl *
4304createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004305 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004306 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004307 // Build struct kmp_task_t_with_privates {
4308 // kmp_task_t task_data;
4309 // .kmp_privates_t. privates;
4310 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004311 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004312 RD->startDefinition();
4313 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004314 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004315 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004316 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004317 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004318}
4319
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004320/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004321/// argument.
4322/// \code
4323/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004324/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004325/// For taskloops:
4326/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004327/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004328/// return 0;
4329/// }
4330/// \endcode
4331static llvm::Value *
4332emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004333 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4334 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004335 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004336 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4337 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004338 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004339 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004340 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4341 ImplicitParamDecl::Other);
4342 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4343 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4344 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004345 Args.push_back(&GtidArg);
4346 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004347 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004348 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004349 llvm::FunctionType *TaskEntryTy =
4350 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004351 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4352 auto *TaskEntry = llvm::Function::Create(
4353 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004354 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004355 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004356 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004357 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4358 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004359
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004360 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004361 // tt,
4362 // For taskloops:
4363 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4364 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004365 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004366 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004367 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4368 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4369 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004370 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004371 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004372 LValue Base =
4373 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004374 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004375 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004376 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4377 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004378
4379 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004380 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4381 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004382 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004383 CGF.ConvertTypeForMem(SharedsPtrTy));
4384
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004385 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4386 llvm::Value *PrivatesParam;
4387 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004388 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004389 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004390 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004391 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004392 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004393 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004394
Alexey Bataev7292c292016-04-25 12:22:29 +00004395 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4396 TaskPrivatesMap,
4397 CGF.Builder
4398 .CreatePointerBitCastOrAddrSpaceCast(
4399 TDBase.getAddress(), CGF.VoidPtrTy)
4400 .getPointer()};
4401 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4402 std::end(CommonArgs));
4403 if (isOpenMPTaskLoopDirective(Kind)) {
4404 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004405 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4406 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004407 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004408 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4409 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004410 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004411 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4412 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004413 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004414 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4415 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004416 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004417 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4418 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004419 CallArgs.push_back(LBParam);
4420 CallArgs.push_back(UBParam);
4421 CallArgs.push_back(StParam);
4422 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004423 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004424 }
4425 CallArgs.push_back(SharedsParam);
4426
Alexey Bataev3c595a62017-08-14 15:01:03 +00004427 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4428 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004429 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4430 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004431 CGF.FinishFunction();
4432 return TaskEntry;
4433}
4434
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004435static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4436 SourceLocation Loc,
4437 QualType KmpInt32Ty,
4438 QualType KmpTaskTWithPrivatesPtrQTy,
4439 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004440 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004441 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004442 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4443 ImplicitParamDecl::Other);
4444 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4445 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4446 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004447 Args.push_back(&GtidArg);
4448 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004449 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004450 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004451 llvm::FunctionType *DestructorFnTy =
4452 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004453 std::string Name =
4454 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004455 auto *DestructorFn =
4456 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004457 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004458 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004459 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004460 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004461 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004462 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004463 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004464
Alexey Bataev31300ed2016-02-04 11:27:03 +00004465 LValue Base = CGF.EmitLoadOfPointerLValue(
4466 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4467 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004468 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004469 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4470 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004471 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004472 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004473 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004474 if (QualType::DestructionKind DtorKind =
4475 Field->getType().isDestructedType()) {
4476 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004477 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4478 }
4479 }
4480 CGF.FinishFunction();
4481 return DestructorFn;
4482}
4483
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004484/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004485/// firstprivate variables.
4486/// \code
4487/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4488/// **noalias priv1,..., <tyn> **noalias privn) {
4489/// *priv1 = &.privates.priv1;
4490/// ...;
4491/// *privn = &.privates.privn;
4492/// }
4493/// \endcode
4494static llvm::Value *
4495emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004496 ArrayRef<const Expr *> PrivateVars,
4497 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004498 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004499 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004500 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004501 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004502 FunctionArgList Args;
4503 ImplicitParamDecl TaskPrivatesArg(
4504 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004505 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4506 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004507 Args.push_back(&TaskPrivatesArg);
4508 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4509 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004510 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004511 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004512 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4513 C.getPointerType(C.getPointerType(E->getType()))
4514 .withConst()
4515 .withRestrict(),
4516 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004517 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004518 PrivateVarsPos[VD] = Counter;
4519 ++Counter;
4520 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004521 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004522 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004523 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4524 C.getPointerType(C.getPointerType(E->getType()))
4525 .withConst()
4526 .withRestrict(),
4527 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004528 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004529 PrivateVarsPos[VD] = Counter;
4530 ++Counter;
4531 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004532 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004533 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004534 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4535 C.getPointerType(C.getPointerType(E->getType()))
4536 .withConst()
4537 .withRestrict(),
4538 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004539 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004540 PrivateVarsPos[VD] = Counter;
4541 ++Counter;
4542 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004543 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004544 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004545 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004546 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004547 std::string Name =
4548 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004549 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004550 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4551 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004552 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004553 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004554 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004555 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004556 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004557 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004558 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004559 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004560
4561 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004562 LValue Base = CGF.EmitLoadOfPointerLValue(
4563 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4564 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004565 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004566 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004567 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4568 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4569 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4570 LValue RefLVal =
4571 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4572 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004573 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004574 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004575 ++Counter;
4576 }
4577 CGF.FinishFunction();
4578 return TaskPrivatesMap;
4579}
4580
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004581static bool stable_sort_comparator(const PrivateDataTy P1,
4582 const PrivateDataTy P2) {
4583 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004584}
4585
Alexey Bataevf93095a2016-05-05 08:46:22 +00004586/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004587static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004588 const OMPExecutableDirective &D,
4589 Address KmpTaskSharedsPtr, LValue TDBase,
4590 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4591 QualType SharedsTy, QualType SharedsPtrTy,
4592 const OMPTaskDataTy &Data,
4593 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004594 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004595 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4596 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004597 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4598 ? OMPD_taskloop
4599 : OMPD_task;
4600 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4601 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004602 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004603 bool IsTargetTask =
4604 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4605 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4606 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4607 // PointersArray and SizesArray. The original variables for these arrays are
4608 // not captured and we get their addresses explicitly.
4609 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004610 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004611 SrcBase = CGF.MakeAddrLValue(
4612 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4613 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4614 SharedsTy);
4615 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004616 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004617 for (const PrivateDataTy &Pair : Privates) {
4618 const VarDecl *VD = Pair.second.PrivateCopy;
4619 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004620 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4621 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004622 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004623 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4624 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004625 // Check if the variable is the target-based BasePointersArray,
4626 // PointersArray or SizesArray.
4627 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004628 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004629 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004630 if (IsTargetTask && !SharedField) {
4631 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4632 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4633 cast<CapturedDecl>(OriginalVD->getDeclContext())
4634 ->getNumParams() == 0 &&
4635 isa<TranslationUnitDecl>(
4636 cast<CapturedDecl>(OriginalVD->getDeclContext())
4637 ->getDeclContext()) &&
4638 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004639 SharedRefLValue =
4640 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4641 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004642 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4643 SharedRefLValue = CGF.MakeAddrLValue(
4644 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4645 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4646 SharedRefLValue.getTBAAInfo());
4647 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004648 if (Type->isArrayType()) {
4649 // Initialize firstprivate array.
4650 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4651 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004652 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004653 } else {
4654 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004655 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004656 CGF.EmitOMPAggregateAssign(
4657 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4658 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4659 Address SrcElement) {
4660 // Clean up any temporaries needed by the initialization.
4661 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4662 InitScope.addPrivate(
4663 Elem, [SrcElement]() -> Address { return SrcElement; });
4664 (void)InitScope.Privatize();
4665 // Emit initialization for single element.
4666 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4667 CGF, &CapturesInfo);
4668 CGF.EmitAnyExprToMem(Init, DestElement,
4669 Init->getType().getQualifiers(),
4670 /*IsInitializer=*/false);
4671 });
4672 }
4673 } else {
4674 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4675 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4676 return SharedRefLValue.getAddress();
4677 });
4678 (void)InitScope.Privatize();
4679 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4680 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4681 /*capturedByInit=*/false);
4682 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004683 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004684 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004685 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004686 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004687 ++FI;
4688 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004689}
4690
4691/// Check if duplication function is required for taskloops.
4692static bool checkInitIsRequired(CodeGenFunction &CGF,
4693 ArrayRef<PrivateDataTy> Privates) {
4694 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004695 for (const PrivateDataTy &Pair : Privates) {
4696 const VarDecl *VD = Pair.second.PrivateCopy;
4697 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004698 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4699 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004700 if (InitRequired)
4701 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004702 }
4703 return InitRequired;
4704}
4705
4706
4707/// Emit task_dup function (for initialization of
4708/// private/firstprivate/lastprivate vars and last_iter flag)
4709/// \code
4710/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4711/// lastpriv) {
4712/// // setup lastprivate flag
4713/// task_dst->last = lastpriv;
4714/// // could be constructor calls here...
4715/// }
4716/// \endcode
4717static llvm::Value *
4718emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4719 const OMPExecutableDirective &D,
4720 QualType KmpTaskTWithPrivatesPtrQTy,
4721 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4722 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4723 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4724 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004725 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004726 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004727 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4728 KmpTaskTWithPrivatesPtrQTy,
4729 ImplicitParamDecl::Other);
4730 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4731 KmpTaskTWithPrivatesPtrQTy,
4732 ImplicitParamDecl::Other);
4733 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4734 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004735 Args.push_back(&DstArg);
4736 Args.push_back(&SrcArg);
4737 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004738 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004739 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004740 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004741 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4742 auto *TaskDup = llvm::Function::Create(
4743 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004744 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004745 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004746 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004747 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4748 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004749
4750 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4751 CGF.GetAddrOfLocalVar(&DstArg),
4752 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4753 // task_dst->liter = lastpriv;
4754 if (WithLastIter) {
4755 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4756 LValue Base = CGF.EmitLValueForField(
4757 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4758 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4759 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4760 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4761 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4762 }
4763
4764 // Emit initial values for private copies (if any).
4765 assert(!Privates.empty());
4766 Address KmpTaskSharedsPtr = Address::invalid();
4767 if (!Data.FirstprivateVars.empty()) {
4768 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4769 CGF.GetAddrOfLocalVar(&SrcArg),
4770 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4771 LValue Base = CGF.EmitLValueForField(
4772 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4773 KmpTaskSharedsPtr = Address(
4774 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4775 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4776 KmpTaskTShareds)),
4777 Loc),
4778 CGF.getNaturalTypeAlignment(SharedsTy));
4779 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004780 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4781 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004782 CGF.FinishFunction();
4783 return TaskDup;
4784}
4785
Alexey Bataev8a831592016-05-10 10:36:51 +00004786/// Checks if destructor function is required to be generated.
4787/// \return true if cleanups are required, false otherwise.
4788static bool
4789checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4790 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004791 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4792 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4793 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004794 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4795 if (NeedsCleanup)
4796 break;
4797 }
4798 return NeedsCleanup;
4799}
4800
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004801CGOpenMPRuntime::TaskResultTy
4802CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4803 const OMPExecutableDirective &D,
4804 llvm::Value *TaskFunction, QualType SharedsTy,
4805 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004806 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004807 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004808 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004809 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004810 for (const Expr *E : Data.PrivateVars) {
4811 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004812 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004813 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004814 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004815 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004816 ++I;
4817 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004818 I = Data.FirstprivateCopies.begin();
4819 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004820 for (const Expr *E : Data.FirstprivateVars) {
4821 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004822 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004823 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004824 PrivateHelpersTy(
4825 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004826 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004827 ++I;
4828 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004829 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004830 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004831 for (const Expr *E : Data.LastprivateVars) {
4832 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004833 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004834 C.getDeclAlign(VD),
4835 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004836 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004837 ++I;
4838 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004839 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004840 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004841 // Build type kmp_routine_entry_t (if not built yet).
4842 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004843 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004844 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4845 if (SavedKmpTaskloopTQTy.isNull()) {
4846 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4847 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4848 }
4849 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004850 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004851 assert((D.getDirectiveKind() == OMPD_task ||
4852 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4853 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4854 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004855 if (SavedKmpTaskTQTy.isNull()) {
4856 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4857 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4858 }
4859 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004860 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004861 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004862 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004863 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004864 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004865 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004866 QualType KmpTaskTWithPrivatesPtrQTy =
4867 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004868 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4869 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4870 KmpTaskTWithPrivatesTy->getPointerTo();
4871 llvm::Value *KmpTaskTWithPrivatesTySize =
4872 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004873 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4874
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004875 // Emit initial values for private copies (if any).
4876 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004877 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004878 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004879 if (!Privates.empty()) {
4880 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004881 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4882 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4883 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004884 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4885 TaskPrivatesMap, TaskPrivatesMapTy);
4886 } else {
4887 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4888 cast<llvm::PointerType>(TaskPrivatesMapTy));
4889 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004890 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4891 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004892 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004893 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4894 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4895 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004896
4897 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4898 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4899 // kmp_routine_entry_t *task_entry);
4900 // Task flags. Format is taken from
4901 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4902 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004903 enum {
4904 TiedFlag = 0x1,
4905 FinalFlag = 0x2,
4906 DestructorsFlag = 0x8,
4907 PriorityFlag = 0x20
4908 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004909 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004910 bool NeedsCleanup = false;
4911 if (!Privates.empty()) {
4912 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4913 if (NeedsCleanup)
4914 Flags = Flags | DestructorsFlag;
4915 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004916 if (Data.Priority.getInt())
4917 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004918 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004919 Data.Final.getPointer()
4920 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004921 CGF.Builder.getInt32(FinalFlag),
4922 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004923 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004924 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004925 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004926 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4927 getThreadID(CGF, Loc), TaskFlags,
4928 KmpTaskTWithPrivatesTySize, SharedsSize,
4929 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4930 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004931 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004932 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004933 llvm::Value *NewTaskNewTaskTTy =
4934 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4935 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004936 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4937 KmpTaskTWithPrivatesQTy);
4938 LValue TDBase =
4939 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004940 // Fill the data in the resulting kmp_task_t record.
4941 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004942 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004943 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004944 KmpTaskSharedsPtr =
4945 Address(CGF.EmitLoadOfScalar(
4946 CGF.EmitLValueForField(
4947 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4948 KmpTaskTShareds)),
4949 Loc),
4950 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004951 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4952 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004953 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004954 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004955 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004956 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004957 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004958 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4959 SharedsTy, SharedsPtrTy, Data, Privates,
4960 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004961 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4962 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4963 Result.TaskDupFn = emitTaskDupFunction(
4964 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4965 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4966 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004967 }
4968 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004969 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4970 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004971 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004972 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004973 const RecordDecl *KmpCmplrdataUD =
4974 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004975 if (NeedsCleanup) {
4976 llvm::Value *DestructorFn = emitDestructorsFunction(
4977 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4978 KmpTaskTWithPrivatesQTy);
4979 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4980 LValue DestructorsLV = CGF.EmitLValueForField(
4981 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4982 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4983 DestructorFn, KmpRoutineEntryPtrTy),
4984 DestructorsLV);
4985 }
4986 // Set priority.
4987 if (Data.Priority.getInt()) {
4988 LValue Data2LV = CGF.EmitLValueForField(
4989 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4990 LValue PriorityLV = CGF.EmitLValueForField(
4991 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4992 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4993 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004994 Result.NewTask = NewTask;
4995 Result.TaskEntry = TaskEntry;
4996 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4997 Result.TDBase = TDBase;
4998 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4999 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00005000}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005001
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005002void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
5003 const OMPExecutableDirective &D,
5004 llvm::Value *TaskFunction,
5005 QualType SharedsTy, Address Shareds,
5006 const Expr *IfCond,
5007 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005008 if (!CGF.HaveInsertPoint())
5009 return;
5010
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005011 TaskResultTy Result =
5012 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5013 llvm::Value *NewTask = Result.NewTask;
5014 llvm::Value *TaskEntry = Result.TaskEntry;
5015 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
5016 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005017 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
5018 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005019 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00005020 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005021 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00005022 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005023 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00005024 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005025 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
5026 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005027 QualType FlagsTy =
5028 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005029 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
5030 if (KmpDependInfoTy.isNull()) {
5031 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
5032 KmpDependInfoRD->startDefinition();
5033 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
5034 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
5035 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
5036 KmpDependInfoRD->completeDefinition();
5037 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005038 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005039 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005040 }
John McCall7f416cc2015-09-08 08:05:57 +00005041 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005042 // Define type kmp_depend_info[<Dependences.size()>];
5043 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005044 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005045 ArrayType::Normal, /*IndexTypeQuals=*/0);
5046 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005047 DependenciesArray =
5048 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005049 for (unsigned I = 0; I < NumDependencies; ++I) {
5050 const Expr *E = Data.Dependences[I].second;
5051 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005052 llvm::Value *Size;
5053 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005054 if (const auto *ASE =
5055 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005056 LValue UpAddrLVal =
5057 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5058 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005059 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005060 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005061 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005062 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5063 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005064 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005065 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005066 }
5067 LValue Base = CGF.MakeAddrLValue(
5068 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005069 KmpDependInfoTy);
5070 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005071 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005072 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005073 CGF.EmitStoreOfScalar(
5074 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5075 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005076 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005077 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005078 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5079 CGF.EmitStoreOfScalar(Size, LenLVal);
5080 // deps[i].flags = <Dependences[i].first>;
5081 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005082 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005083 case OMPC_DEPEND_in:
5084 DepKind = DepIn;
5085 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005086 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005087 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005088 case OMPC_DEPEND_inout:
5089 DepKind = DepInOut;
5090 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005091 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005092 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005093 case OMPC_DEPEND_unknown:
5094 llvm_unreachable("Unknown task dependence type");
5095 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005096 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005097 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5098 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5099 FlagsLVal);
5100 }
John McCall7f416cc2015-09-08 08:05:57 +00005101 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5102 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005103 CGF.VoidPtrTy);
5104 }
5105
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005106 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005107 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005108 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5109 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5110 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5111 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005112 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5113 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005114 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5115 llvm::Value *DepTaskArgs[7];
5116 if (NumDependencies) {
5117 DepTaskArgs[0] = UpLoc;
5118 DepTaskArgs[1] = ThreadID;
5119 DepTaskArgs[2] = NewTask;
5120 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5121 DepTaskArgs[4] = DependenciesArray.getPointer();
5122 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5123 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5124 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005125 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5126 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005127 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005128 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005129 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005130 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005131 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5132 }
John McCall7f416cc2015-09-08 08:05:57 +00005133 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005134 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005135 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005136 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005137 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005138 TaskArgs);
5139 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005140 // Check if parent region is untied and build return for untied task;
5141 if (auto *Region =
5142 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5143 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005144 };
John McCall7f416cc2015-09-08 08:05:57 +00005145
5146 llvm::Value *DepWaitTaskArgs[6];
5147 if (NumDependencies) {
5148 DepWaitTaskArgs[0] = UpLoc;
5149 DepWaitTaskArgs[1] = ThreadID;
5150 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5151 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5152 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5153 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5154 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005155 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005156 NumDependencies, &DepWaitTaskArgs,
5157 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005158 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005159 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5160 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5161 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5162 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5163 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005164 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005165 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005166 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005167 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005168 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5169 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005170 Action.Enter(CGF);
5171 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005172 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005173 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005174 };
5175
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005176 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5177 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005178 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5179 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005180 RegionCodeGenTy RCG(CodeGen);
5181 CommonActionTy Action(
5182 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5183 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5184 RCG.setAction(Action);
5185 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005186 };
John McCall7f416cc2015-09-08 08:05:57 +00005187
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005188 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005189 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005190 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005191 RegionCodeGenTy ThenRCG(ThenCodeGen);
5192 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005193 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005194}
5195
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005196void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5197 const OMPLoopDirective &D,
5198 llvm::Value *TaskFunction,
5199 QualType SharedsTy, Address Shareds,
5200 const Expr *IfCond,
5201 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005202 if (!CGF.HaveInsertPoint())
5203 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005204 TaskResultTy Result =
5205 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005206 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005207 // libcall.
5208 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5209 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5210 // sched, kmp_uint64 grainsize, void *task_dup);
5211 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5212 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5213 llvm::Value *IfVal;
5214 if (IfCond) {
5215 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5216 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005217 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005218 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005219 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005220
5221 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005222 Result.TDBase,
5223 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005224 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005225 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5226 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5227 /*IsInitializer=*/true);
5228 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005229 Result.TDBase,
5230 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005231 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005232 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5233 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5234 /*IsInitializer=*/true);
5235 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005236 Result.TDBase,
5237 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005238 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005239 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5240 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5241 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005242 // Store reductions address.
5243 LValue RedLVal = CGF.EmitLValueForField(
5244 Result.TDBase,
5245 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005246 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005247 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005248 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005249 CGF.EmitNullInitialization(RedLVal.getAddress(),
5250 CGF.getContext().VoidPtrTy);
5251 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005252 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005253 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005254 UpLoc,
5255 ThreadID,
5256 Result.NewTask,
5257 IfVal,
5258 LBLVal.getPointer(),
5259 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005260 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataevac6e4de2018-10-24 19:06:37 +00005261 llvm::ConstantInt::getSigned(
5262 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005263 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005264 CGF.IntTy, Data.Schedule.getPointer()
5265 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005266 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005267 Data.Schedule.getPointer()
5268 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005269 /*isSigned=*/false)
5270 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005271 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5272 Result.TaskDupFn, CGF.VoidPtrTy)
5273 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005274 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5275}
5276
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005277/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005278/// array sections) LHS op = RHS.
5279/// \param Type Type of array.
5280/// \param LHSVar Variable on the left side of the reduction operation
5281/// (references element of array in original variable).
5282/// \param RHSVar Variable on the right side of the reduction operation
5283/// (references element of array in original variable).
5284/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5285/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005286static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005287 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5288 const VarDecl *RHSVar,
5289 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5290 const Expr *, const Expr *)> &RedOpGen,
5291 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5292 const Expr *UpExpr = nullptr) {
5293 // Perform element-by-element initialization.
5294 QualType ElementTy;
5295 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5296 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5297
5298 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005299 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5300 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005301
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005302 llvm::Value *RHSBegin = RHSAddr.getPointer();
5303 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005304 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005305 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005306 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005307 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5308 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5309 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005310 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5311 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5312
5313 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005314 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005315 CGF.EmitBlock(BodyBB);
5316
5317 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5318
5319 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5320 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5321 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5322 Address RHSElementCurrent =
5323 Address(RHSElementPHI,
5324 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5325
5326 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5327 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5328 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5329 Address LHSElementCurrent =
5330 Address(LHSElementPHI,
5331 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5332
5333 // Emit copy.
5334 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005335 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5336 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005337 Scope.Privatize();
5338 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5339 Scope.ForceCleanup();
5340
5341 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005342 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005343 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005344 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005345 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5346 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005347 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005348 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5349 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5350 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5351 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5352
5353 // Done.
5354 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5355}
5356
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005357/// Emit reduction combiner. If the combiner is a simple expression emit it as
5358/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5359/// UDR combiner function.
5360static void emitReductionCombiner(CodeGenFunction &CGF,
5361 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005362 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5363 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5364 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005365 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005366 if (const auto *DRD =
5367 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005368 std::pair<llvm::Function *, llvm::Function *> Reduction =
5369 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5370 RValue Func = RValue::get(Reduction.first);
5371 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5372 CGF.EmitIgnoredExpr(ReductionOp);
5373 return;
5374 }
5375 CGF.EmitIgnoredExpr(ReductionOp);
5376}
5377
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005378llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005379 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5380 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5381 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005382 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005383
5384 // void reduction_func(void *LHSArg, void *RHSArg);
5385 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005386 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5387 ImplicitParamDecl::Other);
5388 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5389 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005390 Args.push_back(&LHSArg);
5391 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005392 const auto &CGFI =
5393 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005394 std::string Name = getName({"omp", "reduction", "reduction_func"});
5395 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5396 llvm::GlobalValue::InternalLinkage, Name,
5397 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005398 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005399 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005400 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005401 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005402
5403 // Dst = (void*[n])(LHSArg);
5404 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005405 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5406 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5407 ArgsType), CGF.getPointerAlign());
5408 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5409 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5410 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005411
5412 // ...
5413 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5414 // ...
5415 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005416 auto IPriv = Privates.begin();
5417 unsigned Idx = 0;
5418 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005419 const auto *RHSVar =
5420 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5421 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005422 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005423 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005424 const auto *LHSVar =
5425 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5426 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005427 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005428 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005429 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005430 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005431 // Get array size and emit VLA type.
5432 ++Idx;
5433 Address Elem =
5434 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5435 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005436 const VariableArrayType *VLA =
5437 CGF.getContext().getAsVariableArrayType(PrivTy);
5438 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005439 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005440 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005441 CGF.EmitVariablyModifiedType(PrivTy);
5442 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005443 }
5444 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005445 IPriv = Privates.begin();
5446 auto ILHS = LHSExprs.begin();
5447 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005448 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005449 if ((*IPriv)->getType()->isArrayType()) {
5450 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005451 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5452 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005453 EmitOMPAggregateReduction(
5454 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5455 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5456 emitReductionCombiner(CGF, E);
5457 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005458 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005459 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005460 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005461 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005462 ++IPriv;
5463 ++ILHS;
5464 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005465 }
5466 Scope.ForceCleanup();
5467 CGF.FinishFunction();
5468 return Fn;
5469}
5470
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005471void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5472 const Expr *ReductionOp,
5473 const Expr *PrivateRef,
5474 const DeclRefExpr *LHS,
5475 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005476 if (PrivateRef->getType()->isArrayType()) {
5477 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005478 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5479 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005480 EmitOMPAggregateReduction(
5481 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5482 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5483 emitReductionCombiner(CGF, ReductionOp);
5484 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005485 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005486 // Emit reduction for array subscript or single variable.
5487 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005488 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005489}
5490
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005491void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005492 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005493 ArrayRef<const Expr *> LHSExprs,
5494 ArrayRef<const Expr *> RHSExprs,
5495 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005496 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005497 if (!CGF.HaveInsertPoint())
5498 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005499
5500 bool WithNowait = Options.WithNowait;
5501 bool SimpleReduction = Options.SimpleReduction;
5502
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005503 // Next code should be emitted for reduction:
5504 //
5505 // static kmp_critical_name lock = { 0 };
5506 //
5507 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5508 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5509 // ...
5510 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5511 // *(Type<n>-1*)rhs[<n>-1]);
5512 // }
5513 //
5514 // ...
5515 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5516 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5517 // RedList, reduce_func, &<lock>)) {
5518 // case 1:
5519 // ...
5520 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5521 // ...
5522 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5523 // break;
5524 // case 2:
5525 // ...
5526 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5527 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005528 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005529 // break;
5530 // default:;
5531 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005532 //
5533 // if SimpleReduction is true, only the next code is generated:
5534 // ...
5535 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5536 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005537
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005538 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005539
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005540 if (SimpleReduction) {
5541 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005542 auto IPriv = Privates.begin();
5543 auto ILHS = LHSExprs.begin();
5544 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005545 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005546 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5547 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005548 ++IPriv;
5549 ++ILHS;
5550 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005551 }
5552 return;
5553 }
5554
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005555 // 1. Build a list of reduction variables.
5556 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005557 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005558 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005559 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005560 // Reserve place for array size.
5561 ++Size;
5562 }
5563 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005564 QualType ReductionArrayTy =
5565 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5566 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005567 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005568 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005569 auto IPriv = Privates.begin();
5570 unsigned Idx = 0;
5571 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005572 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005573 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005574 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005575 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005576 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5577 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005578 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005579 // Store array size.
5580 ++Idx;
5581 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5582 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005583 llvm::Value *Size = CGF.Builder.CreateIntCast(
5584 CGF.getVLASize(
5585 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005586 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005587 CGF.SizeTy, /*isSigned=*/false);
5588 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5589 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005590 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005591 }
5592
5593 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005594 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005595 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5596 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005597
5598 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005599 std::string Name = getName({"reduction"});
5600 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005601
5602 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5603 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005604 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5605 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5606 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5607 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005608 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005609 llvm::Value *Args[] = {
5610 IdentTLoc, // ident_t *<loc>
5611 ThreadId, // i32 <gtid>
5612 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5613 ReductionArrayTySize, // size_type sizeof(RedList)
5614 RL, // void *RedList
5615 ReductionFn, // void (*) (void *, void *) <reduce_func>
5616 Lock // kmp_critical_name *&<lock>
5617 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005618 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005619 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5620 : OMPRTL__kmpc_reduce),
5621 Args);
5622
5623 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005624 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5625 llvm::SwitchInst *SwInst =
5626 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005627
5628 // 6. Build case 1:
5629 // ...
5630 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5631 // ...
5632 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5633 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005634 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005635 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5636 CGF.EmitBlock(Case1BB);
5637
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005638 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5639 llvm::Value *EndArgs[] = {
5640 IdentTLoc, // ident_t *<loc>
5641 ThreadId, // i32 <gtid>
5642 Lock // kmp_critical_name *&<lock>
5643 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005644 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5645 CodeGenFunction &CGF, PrePostActionTy &Action) {
5646 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005647 auto IPriv = Privates.begin();
5648 auto ILHS = LHSExprs.begin();
5649 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005650 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005651 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5652 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005653 ++IPriv;
5654 ++ILHS;
5655 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005656 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005657 };
5658 RegionCodeGenTy RCG(CodeGen);
5659 CommonActionTy Action(
5660 nullptr, llvm::None,
5661 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5662 : OMPRTL__kmpc_end_reduce),
5663 EndArgs);
5664 RCG.setAction(Action);
5665 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005666
5667 CGF.EmitBranch(DefaultBB);
5668
5669 // 7. Build case 2:
5670 // ...
5671 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5672 // ...
5673 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005674 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005675 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5676 CGF.EmitBlock(Case2BB);
5677
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005678 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5679 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005680 auto ILHS = LHSExprs.begin();
5681 auto IRHS = RHSExprs.begin();
5682 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005683 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005684 const Expr *XExpr = nullptr;
5685 const Expr *EExpr = nullptr;
5686 const Expr *UpExpr = nullptr;
5687 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005688 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005689 if (BO->getOpcode() == BO_Assign) {
5690 XExpr = BO->getLHS();
5691 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005692 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005693 }
5694 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005695 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005696 if (RHSExpr) {
5697 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005698 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005699 RHSExpr->IgnoreParenImpCasts())) {
5700 // If this is a conditional operator, analyze its condition for
5701 // min/max reduction operator.
5702 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005703 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005704 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005705 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5706 EExpr = BORHS->getRHS();
5707 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005708 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005709 }
5710 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005711 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005712 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005713 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5714 const Expr *EExpr, const Expr *UpExpr) {
5715 LValue X = CGF.EmitLValue(XExpr);
5716 RValue E;
5717 if (EExpr)
5718 E = CGF.EmitAnyExpr(EExpr);
5719 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005720 X, E, BO, /*IsXLHSInRHSPart=*/true,
5721 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005722 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005723 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5724 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005725 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005726 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5727 CGF.emitOMPSimpleStore(
5728 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5729 VD->getType().getNonReferenceType(), Loc);
5730 return LHSTemp;
5731 });
5732 (void)PrivateScope.Privatize();
5733 return CGF.EmitAnyExpr(UpExpr);
5734 });
5735 };
5736 if ((*IPriv)->getType()->isArrayType()) {
5737 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005738 const auto *RHSVar =
5739 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005740 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5741 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005742 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005743 // Emit atomic reduction for array subscript or single variable.
5744 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005745 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005746 } else {
5747 // Emit as a critical region.
5748 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005749 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005750 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005751 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005752 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005753 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005754 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5755 Action.Enter(CGF);
5756 emitReductionCombiner(CGF, E);
5757 },
5758 Loc);
5759 };
5760 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005761 const auto *LHSVar =
5762 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5763 const auto *RHSVar =
5764 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005765 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5766 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005767 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005768 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005769 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005770 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005771 ++ILHS;
5772 ++IRHS;
5773 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005774 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005775 };
5776 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5777 if (!WithNowait) {
5778 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5779 llvm::Value *EndArgs[] = {
5780 IdentTLoc, // ident_t *<loc>
5781 ThreadId, // i32 <gtid>
5782 Lock // kmp_critical_name *&<lock>
5783 };
5784 CommonActionTy Action(nullptr, llvm::None,
5785 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5786 EndArgs);
5787 AtomicRCG.setAction(Action);
5788 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005789 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005790 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005791 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005792
5793 CGF.EmitBranch(DefaultBB);
5794 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5795}
5796
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005797/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005798/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5799static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5800 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005801 SmallString<256> Buffer;
5802 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005803 const clang::DeclRefExpr *DE;
5804 const VarDecl *D = ::getBaseDecl(Ref, DE);
5805 if (!D)
5806 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5807 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005808 std::string Name = CGM.getOpenMPRuntime().getName(
5809 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5810 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005811 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005812 return Out.str();
5813}
5814
5815/// Emits reduction initializer function:
5816/// \code
5817/// void @.red_init(void* %arg) {
5818/// %0 = bitcast void* %arg to <type>*
5819/// store <type> <init>, <type>* %0
5820/// ret void
5821/// }
5822/// \endcode
5823static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5824 SourceLocation Loc,
5825 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005826 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005827 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005828 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5829 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005830 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005831 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005832 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005833 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005834 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005835 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005836 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005837 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005838 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005839 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005840 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005841 Address PrivateAddr = CGF.EmitLoadOfPointer(
5842 CGF.GetAddrOfLocalVar(&Param),
5843 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5844 llvm::Value *Size = nullptr;
5845 // If the size of the reduction item is non-constant, load it from global
5846 // threadprivate variable.
5847 if (RCG.getSizes(N).second) {
5848 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5849 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005850 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005851 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5852 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005853 }
5854 RCG.emitAggregateType(CGF, N, Size);
5855 LValue SharedLVal;
5856 // If initializer uses initializer from declare reduction construct, emit a
5857 // pointer to the address of the original reduction item (reuired by reduction
5858 // initializer)
5859 if (RCG.usesReductionInitializer(N)) {
5860 Address SharedAddr =
5861 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5862 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005863 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005864 SharedAddr = CGF.EmitLoadOfPointer(
5865 SharedAddr,
5866 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005867 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5868 } else {
5869 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5870 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5871 CGM.getContext().VoidPtrTy);
5872 }
5873 // Emit the initializer:
5874 // %0 = bitcast void* %arg to <type>*
5875 // store <type> <init>, <type>* %0
5876 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5877 [](CodeGenFunction &) { return false; });
5878 CGF.FinishFunction();
5879 return Fn;
5880}
5881
5882/// Emits reduction combiner function:
5883/// \code
5884/// void @.red_comb(void* %arg0, void* %arg1) {
5885/// %lhs = bitcast void* %arg0 to <type>*
5886/// %rhs = bitcast void* %arg1 to <type>*
5887/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5888/// store <type> %2, <type>* %lhs
5889/// ret void
5890/// }
5891/// \endcode
5892static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5893 SourceLocation Loc,
5894 ReductionCodeGen &RCG, unsigned N,
5895 const Expr *ReductionOp,
5896 const Expr *LHS, const Expr *RHS,
5897 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005898 ASTContext &C = CGM.getContext();
5899 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5900 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005901 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005902 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5903 C.VoidPtrTy, ImplicitParamDecl::Other);
5904 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5905 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005906 Args.emplace_back(&ParamInOut);
5907 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005908 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005909 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005910 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005911 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005912 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005913 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005914 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005915 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005916 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005917 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005918 llvm::Value *Size = nullptr;
5919 // If the size of the reduction item is non-constant, load it from global
5920 // threadprivate variable.
5921 if (RCG.getSizes(N).second) {
5922 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5923 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005924 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005925 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5926 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005927 }
5928 RCG.emitAggregateType(CGF, N, Size);
5929 // Remap lhs and rhs variables to the addresses of the function arguments.
5930 // %lhs = bitcast void* %arg0 to <type>*
5931 // %rhs = bitcast void* %arg1 to <type>*
5932 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005933 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005934 // Pull out the pointer to the variable.
5935 Address PtrAddr = CGF.EmitLoadOfPointer(
5936 CGF.GetAddrOfLocalVar(&ParamInOut),
5937 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5938 return CGF.Builder.CreateElementBitCast(
5939 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5940 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005941 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005942 // Pull out the pointer to the variable.
5943 Address PtrAddr = CGF.EmitLoadOfPointer(
5944 CGF.GetAddrOfLocalVar(&ParamIn),
5945 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5946 return CGF.Builder.CreateElementBitCast(
5947 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5948 });
5949 PrivateScope.Privatize();
5950 // Emit the combiner body:
5951 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5952 // store <type> %2, <type>* %lhs
5953 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5954 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5955 cast<DeclRefExpr>(RHS));
5956 CGF.FinishFunction();
5957 return Fn;
5958}
5959
5960/// Emits reduction finalizer function:
5961/// \code
5962/// void @.red_fini(void* %arg) {
5963/// %0 = bitcast void* %arg to <type>*
5964/// <destroy>(<type>* %0)
5965/// ret void
5966/// }
5967/// \endcode
5968static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5969 SourceLocation Loc,
5970 ReductionCodeGen &RCG, unsigned N) {
5971 if (!RCG.needCleanups(N))
5972 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005973 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005974 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005975 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5976 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005977 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005978 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005979 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005980 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005981 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005982 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005983 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005984 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005985 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005986 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005987 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005988 Address PrivateAddr = CGF.EmitLoadOfPointer(
5989 CGF.GetAddrOfLocalVar(&Param),
5990 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5991 llvm::Value *Size = nullptr;
5992 // If the size of the reduction item is non-constant, load it from global
5993 // threadprivate variable.
5994 if (RCG.getSizes(N).second) {
5995 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5996 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005997 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005998 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5999 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006000 }
6001 RCG.emitAggregateType(CGF, N, Size);
6002 // Emit the finalizer body:
6003 // <destroy>(<type>* %0)
6004 RCG.emitCleanups(CGF, N, PrivateAddr);
6005 CGF.FinishFunction();
6006 return Fn;
6007}
6008
6009llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
6010 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
6011 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
6012 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
6013 return nullptr;
6014
6015 // Build typedef struct:
6016 // kmp_task_red_input {
6017 // void *reduce_shar; // shared reduction item
6018 // size_t reduce_size; // size of data item
6019 // void *reduce_init; // data initialization routine
6020 // void *reduce_fini; // data finalization routine
6021 // void *reduce_comb; // data combiner routine
6022 // kmp_task_red_flags_t flags; // flags for additional info from compiler
6023 // } kmp_task_red_input_t;
6024 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006025 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006026 RD->startDefinition();
6027 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6028 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
6029 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6030 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6031 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6032 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6033 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6034 RD->completeDefinition();
6035 QualType RDType = C.getRecordType(RD);
6036 unsigned Size = Data.ReductionVars.size();
6037 llvm::APInt ArraySize(/*numBits=*/64, Size);
6038 QualType ArrayRDType = C.getConstantArrayType(
6039 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6040 // kmp_task_red_input_t .rd_input.[Size];
6041 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6042 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6043 Data.ReductionOps);
6044 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6045 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6046 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6047 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6048 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6049 TaskRedInput.getPointer(), Idxs,
6050 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6051 ".rd_input.gep.");
6052 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6053 // ElemLVal.reduce_shar = &Shareds[Cnt];
6054 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6055 RCG.emitSharedLValue(CGF, Cnt);
6056 llvm::Value *CastedShared =
6057 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6058 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6059 RCG.emitAggregateType(CGF, Cnt);
6060 llvm::Value *SizeValInChars;
6061 llvm::Value *SizeVal;
6062 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6063 // We use delayed creation/initialization for VLAs, array sections and
6064 // custom reduction initializations. It is required because runtime does not
6065 // provide the way to pass the sizes of VLAs/array sections to
6066 // initializer/combiner/finalizer functions and does not pass the pointer to
6067 // original reduction item to the initializer. Instead threadprivate global
6068 // variables are used to store these values and use them in the functions.
6069 bool DelayedCreation = !!SizeVal;
6070 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6071 /*isSigned=*/false);
6072 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6073 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6074 // ElemLVal.reduce_init = init;
6075 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6076 llvm::Value *InitAddr =
6077 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6078 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6079 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6080 // ElemLVal.reduce_fini = fini;
6081 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6082 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6083 llvm::Value *FiniAddr = Fini
6084 ? CGF.EmitCastToVoidPtr(Fini)
6085 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6086 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6087 // ElemLVal.reduce_comb = comb;
6088 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6089 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6090 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6091 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6092 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6093 // ElemLVal.flags = 0;
6094 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6095 if (DelayedCreation) {
6096 CGF.EmitStoreOfScalar(
6097 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6098 FlagsLVal);
6099 } else
6100 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6101 }
6102 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6103 // *data);
6104 llvm::Value *Args[] = {
6105 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6106 /*isSigned=*/true),
6107 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6108 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6109 CGM.VoidPtrTy)};
6110 return CGF.EmitRuntimeCall(
6111 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6112}
6113
6114void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6115 SourceLocation Loc,
6116 ReductionCodeGen &RCG,
6117 unsigned N) {
6118 auto Sizes = RCG.getSizes(N);
6119 // Emit threadprivate global variable if the type is non-constant
6120 // (Sizes.second = nullptr).
6121 if (Sizes.second) {
6122 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6123 /*isSigned=*/false);
6124 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6125 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006126 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006127 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6128 }
6129 // Store address of the original reduction item if custom initializer is used.
6130 if (RCG.usesReductionInitializer(N)) {
6131 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6132 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006133 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006134 CGF.Builder.CreateStore(
6135 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6136 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6137 SharedAddr, /*IsVolatile=*/false);
6138 }
6139}
6140
6141Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6142 SourceLocation Loc,
6143 llvm::Value *ReductionsPtr,
6144 LValue SharedLVal) {
6145 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6146 // *d);
6147 llvm::Value *Args[] = {
6148 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6149 /*isSigned=*/true),
6150 ReductionsPtr,
6151 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6152 CGM.VoidPtrTy)};
6153 return Address(
6154 CGF.EmitRuntimeCall(
6155 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6156 SharedLVal.getAlignment());
6157}
6158
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006159void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6160 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006161 if (!CGF.HaveInsertPoint())
6162 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006163 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6164 // global_tid);
6165 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6166 // Ignore return result until untied tasks are supported.
6167 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006168 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6169 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006170}
6171
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006172void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006173 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006174 const RegionCodeGenTy &CodeGen,
6175 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006176 if (!CGF.HaveInsertPoint())
6177 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006178 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006179 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006180}
6181
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006182namespace {
6183enum RTCancelKind {
6184 CancelNoreq = 0,
6185 CancelParallel = 1,
6186 CancelLoop = 2,
6187 CancelSections = 3,
6188 CancelTaskgroup = 4
6189};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006190} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006191
6192static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6193 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006194 if (CancelRegion == OMPD_parallel)
6195 CancelKind = CancelParallel;
6196 else if (CancelRegion == OMPD_for)
6197 CancelKind = CancelLoop;
6198 else if (CancelRegion == OMPD_sections)
6199 CancelKind = CancelSections;
6200 else {
6201 assert(CancelRegion == OMPD_taskgroup);
6202 CancelKind = CancelTaskgroup;
6203 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006204 return CancelKind;
6205}
6206
6207void CGOpenMPRuntime::emitCancellationPointCall(
6208 CodeGenFunction &CGF, SourceLocation Loc,
6209 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006210 if (!CGF.HaveInsertPoint())
6211 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006212 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6213 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006214 if (auto *OMPRegionInfo =
6215 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006216 // For 'cancellation point taskgroup', the task region info may not have a
6217 // cancel. This may instead happen in another adjacent task.
6218 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006219 llvm::Value *Args[] = {
6220 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6221 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006222 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006223 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006224 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6225 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006226 // exit from construct;
6227 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006228 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6229 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6230 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006231 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6232 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006233 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006234 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006235 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006236 CGF.EmitBranchThroughCleanup(CancelDest);
6237 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6238 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006239 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006240}
6241
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006242void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006243 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006244 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006245 if (!CGF.HaveInsertPoint())
6246 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006247 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6248 // kmp_int32 cncl_kind);
6249 if (auto *OMPRegionInfo =
6250 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006251 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6252 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006253 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006254 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006255 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006256 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6257 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006258 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006259 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006260 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006261 // exit from construct;
6262 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006263 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6264 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6265 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006266 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6267 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006268 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006269 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006270 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6271 CGF.EmitBranchThroughCleanup(CancelDest);
6272 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6273 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006274 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006275 emitOMPIfClause(CGF, IfCond, ThenGen,
6276 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006277 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006278 RegionCodeGenTy ThenRCG(ThenGen);
6279 ThenRCG(CGF);
6280 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006281 }
6282}
Samuel Antaobed3c462015-10-02 16:14:20 +00006283
Samuel Antaoee8fb302016-01-06 13:42:12 +00006284void CGOpenMPRuntime::emitTargetOutlinedFunction(
6285 const OMPExecutableDirective &D, StringRef ParentName,
6286 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006287 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006288 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006289 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6290 IsOffloadEntry, CodeGen);
6291}
6292
6293void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6294 const OMPExecutableDirective &D, StringRef ParentName,
6295 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6296 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006297 // Create a unique name for the entry function using the source location
6298 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006299 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006300 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006301 //
6302 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006303 // mangled name of the function that encloses the target region and BB is the
6304 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006305
6306 unsigned DeviceID;
6307 unsigned FileID;
6308 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006309 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006310 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006311 SmallString<64> EntryFnName;
6312 {
6313 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006314 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6315 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006316 }
6317
Alexey Bataev475a7442018-01-12 19:39:11 +00006318 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006319
Samuel Antaobed3c462015-10-02 16:14:20 +00006320 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006321 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006322 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006323
Samuel Antao6d004262016-06-16 18:39:34 +00006324 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006325
6326 // If this target outline function is not an offload entry, we don't need to
6327 // register it.
6328 if (!IsOffloadEntry)
6329 return;
6330
6331 // The target region ID is used by the runtime library to identify the current
6332 // target region, so it only has to be unique and not necessarily point to
6333 // anything. It could be the pointer to the outlined function that implements
6334 // the target region, but we aren't using that so that the compiler doesn't
6335 // need to keep that, and could therefore inline the host function if proven
6336 // worthwhile during optimization. In the other hand, if emitting code for the
6337 // device, the ID has to be the function address so that it can retrieved from
6338 // the offloading entry and launched by the runtime library. We also mark the
6339 // outlined function to have external linkage in case we are emitting code for
6340 // the device, because these functions will be entry points to the device.
6341
6342 if (CGM.getLangOpts().OpenMPIsDevice) {
6343 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006344 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006345 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006346 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006347 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006348 OutlinedFnID = new llvm::GlobalVariable(
6349 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006350 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006351 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006352 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006353
6354 // Register the information for the entry associated with this target region.
6355 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006356 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006357 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006358}
6359
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006360/// discard all CompoundStmts intervening between two constructs
6361static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006362 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006363 Body = CS->body_front();
6364
6365 return Body;
6366}
6367
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006368/// Emit the number of teams for a target directive. Inspect the num_teams
6369/// clause associated with a teams construct combined or closely nested
6370/// with the target directive.
6371///
6372/// Emit a team of size one for directives such as 'target parallel' that
6373/// have no associated teams construct.
6374///
6375/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006376static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006377emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6378 CodeGenFunction &CGF,
6379 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006380 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6381 "teams directive expected to be "
6382 "emitted only for the host!");
6383
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006384 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006385
6386 // If the target directive is combined with a teams directive:
6387 // Return the value in the num_teams clause, if any.
6388 // Otherwise, return 0 to denote the runtime default.
6389 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6390 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6391 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006392 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6393 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006394 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6395 /*IsSigned=*/true);
6396 }
6397
6398 // The default value is 0.
6399 return Bld.getInt32(0);
6400 }
6401
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006402 // If the target directive is combined with a parallel directive but not a
6403 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006404 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6405 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006406
6407 // If the current target region has a teams region enclosed, we need to get
6408 // the number of teams to pass to the runtime function call. This is done
6409 // by generating the expression in a inlined region. This is required because
6410 // the expression is captured in the enclosing target environment when the
6411 // teams directive is not combined with target.
6412
Alexey Bataev475a7442018-01-12 19:39:11 +00006413 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006414
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006415 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006416 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006417 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006418 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006419 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6420 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6421 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6422 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6423 /*IsSigned=*/true);
6424 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006425
Alexey Bataev50a1c782017-12-01 21:31:08 +00006426 // If we have an enclosed teams directive but no num_teams clause we use
6427 // the default value 0.
6428 return Bld.getInt32(0);
6429 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006430 }
6431
6432 // No teams associated with the directive.
6433 return nullptr;
6434}
6435
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006436/// Emit the number of threads for a target directive. Inspect the
6437/// thread_limit clause associated with a teams construct combined or closely
6438/// nested with the target directive.
6439///
6440/// Emit the num_threads clause for directives such as 'target parallel' that
6441/// have no associated teams construct.
6442///
6443/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006444static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006445emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6446 CodeGenFunction &CGF,
6447 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006448 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6449 "teams directive expected to be "
6450 "emitted only for the host!");
6451
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006452 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006453
6454 //
6455 // If the target directive is combined with a teams directive:
6456 // Return the value in the thread_limit clause, if any.
6457 //
6458 // If the target directive is combined with a parallel directive:
6459 // Return the value in the num_threads clause, if any.
6460 //
6461 // If both clauses are set, select the minimum of the two.
6462 //
6463 // If neither teams or parallel combined directives set the number of threads
6464 // in a team, return 0 to denote the runtime default.
6465 //
6466 // If this is not a teams directive return nullptr.
6467
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006468 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6469 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006470 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6471 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006472 llvm::Value *ThreadLimitVal = nullptr;
6473
6474 if (const auto *ThreadLimitClause =
6475 D.getSingleClause<OMPThreadLimitClause>()) {
6476 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006477 llvm::Value *ThreadLimit =
6478 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6479 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006480 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6481 /*IsSigned=*/true);
6482 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006483
6484 if (const auto *NumThreadsClause =
6485 D.getSingleClause<OMPNumThreadsClause>()) {
6486 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6487 llvm::Value *NumThreads =
6488 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6489 /*IgnoreResultAssign*/ true);
6490 NumThreadsVal =
6491 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6492 }
6493
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006494 // Select the lesser of thread_limit and num_threads.
6495 if (NumThreadsVal)
6496 ThreadLimitVal = ThreadLimitVal
6497 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6498 ThreadLimitVal),
6499 NumThreadsVal, ThreadLimitVal)
6500 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006501
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006502 // Set default value passed to the runtime if either teams or a target
6503 // parallel type directive is found but no clause is specified.
6504 if (!ThreadLimitVal)
6505 ThreadLimitVal = DefaultThreadLimitVal;
6506
6507 return ThreadLimitVal;
6508 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006509
Samuel Antaob68e2db2016-03-03 16:20:23 +00006510 // If the current target region has a teams region enclosed, we need to get
6511 // the thread limit to pass to the runtime function call. This is done
6512 // by generating the expression in a inlined region. This is required because
6513 // the expression is captured in the enclosing target environment when the
6514 // teams directive is not combined with target.
6515
Alexey Bataev475a7442018-01-12 19:39:11 +00006516 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006517
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006518 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006519 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006520 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006521 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006522 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6523 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6524 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6525 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6526 /*IsSigned=*/true);
6527 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006528
Alexey Bataev50a1c782017-12-01 21:31:08 +00006529 // If we have an enclosed teams directive but no thread_limit clause we
6530 // use the default value 0.
6531 return CGF.Builder.getInt32(0);
6532 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006533 }
6534
6535 // No teams associated with the directive.
6536 return nullptr;
6537}
6538
Samuel Antao86ace552016-04-27 22:40:57 +00006539namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006540LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6541
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006542// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006543// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6544// It provides a convenient interface to obtain the information and generate
6545// code for that information.
6546class MappableExprsHandler {
6547public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006548 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006549 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006550 enum OpenMPOffloadMappingFlags : uint64_t {
6551 /// No flags
6552 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006553 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006554 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006555 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006556 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006557 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006558 /// if it was already mapped before.
6559 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006560 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006561 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006562 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006563 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006564 /// pointer and the pointee should be mapped.
6565 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006566 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006567 /// passed to the target kernel as an argument.
6568 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006569 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006570 /// in the current position for the data being mapped. Used when we have the
6571 /// use_device_ptr clause.
6572 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006573 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006574 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006575 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006576 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006577 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006578 /// Implicit map
6579 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006580 /// The 16 MSBs of the flags indicate whether the entry is member of some
6581 /// struct/class.
6582 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6583 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006584 };
6585
Samuel Antaocc10b852016-07-28 14:23:26 +00006586 /// Class that associates information with a base pointer to be passed to the
6587 /// runtime library.
6588 class BasePointerInfo {
6589 /// The base pointer.
6590 llvm::Value *Ptr = nullptr;
6591 /// The base declaration that refers to this device pointer, or null if
6592 /// there is none.
6593 const ValueDecl *DevPtrDecl = nullptr;
6594
6595 public:
6596 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6597 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6598 llvm::Value *operator*() const { return Ptr; }
6599 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6600 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6601 };
6602
Alexey Bataevb3638132018-07-19 16:34:13 +00006603 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6604 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6605 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6606
6607 /// Map between a struct and the its lowest & highest elements which have been
6608 /// mapped.
6609 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6610 /// HE(FieldIndex, Pointer)}
6611 struct StructRangeInfoTy {
6612 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6613 0, Address::invalid()};
6614 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6615 0, Address::invalid()};
6616 Address Base = Address::invalid();
6617 };
Samuel Antao86ace552016-04-27 22:40:57 +00006618
6619private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006620 /// Kind that defines how a device pointer has to be returned.
6621 struct MapInfo {
6622 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6623 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6624 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6625 bool ReturnDevicePointer = false;
6626 bool IsImplicit = false;
6627
6628 MapInfo() = default;
6629 MapInfo(
6630 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6631 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6632 bool ReturnDevicePointer, bool IsImplicit)
6633 : Components(Components), MapType(MapType),
6634 MapTypeModifier(MapTypeModifier),
6635 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6636 };
6637
6638 /// If use_device_ptr is used on a pointer which is a struct member and there
6639 /// is no map information about it, then emission of that entry is deferred
6640 /// until the whole struct has been processed.
6641 struct DeferredDevicePtrEntryTy {
6642 const Expr *IE = nullptr;
6643 const ValueDecl *VD = nullptr;
6644
6645 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6646 : IE(IE), VD(VD) {}
6647 };
6648
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006649 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006650 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006651
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006652 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006653 CodeGenFunction &CGF;
6654
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006655 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006656 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6657
Samuel Antao6890b092016-07-28 14:25:09 +00006658 /// Map between device pointer declarations and their expression components.
6659 /// The key value for declarations in 'this' is null.
6660 llvm::DenseMap<
6661 const ValueDecl *,
6662 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6663 DevPointersMap;
6664
Samuel Antao86ace552016-04-27 22:40:57 +00006665 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006666 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006667
6668 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006669 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006670 ExprTy = RefTy->getPointeeType().getCanonicalType();
6671
6672 // Given that an array section is considered a built-in type, we need to
6673 // do the calculation based on the length of the section instead of relying
6674 // on CGF.getTypeSize(E->getType()).
6675 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6676 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6677 OAE->getBase()->IgnoreParenImpCasts())
6678 .getCanonicalType();
6679
6680 // If there is no length associated with the expression, that means we
6681 // are using the whole length of the base.
6682 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6683 return CGF.getTypeSize(BaseTy);
6684
6685 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006686 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006687 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006688 } else {
6689 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006690 assert(ATy && "Expecting array type if not a pointer type.");
6691 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6692 }
6693
6694 // If we don't have a length at this point, that is because we have an
6695 // array section with a single element.
6696 if (!OAE->getLength())
6697 return ElemSize;
6698
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006699 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006700 LengthVal =
6701 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6702 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6703 }
6704 return CGF.getTypeSize(ExprTy);
6705 }
6706
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006707 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006708 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006709 /// map as the first one of a series of maps that relate to the same map
6710 /// expression.
Alexey Bataevb3638132018-07-19 16:34:13 +00006711 OpenMPOffloadMappingFlags getMapTypeBits(OpenMPMapClauseKind MapType,
6712 OpenMPMapClauseKind MapTypeModifier,
6713 bool IsImplicit, bool AddPtrFlag,
6714 bool AddIsTargetParamFlag) const {
6715 OpenMPOffloadMappingFlags Bits =
6716 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006717 switch (MapType) {
6718 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006719 case OMPC_MAP_release:
6720 // alloc and release is the default behavior in the runtime library, i.e.
6721 // if we don't pass any bits alloc/release that is what the runtime is
6722 // going to do. Therefore, we don't need to signal anything for these two
6723 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006724 break;
6725 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006726 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006727 break;
6728 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006729 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006730 break;
6731 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006732 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006733 break;
6734 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006735 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006736 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006737 case OMPC_MAP_always:
6738 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006739 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006740 }
6741 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006742 Bits |= OMP_MAP_PTR_AND_OBJ;
6743 if (AddIsTargetParamFlag)
6744 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006745 if (MapTypeModifier == OMPC_MAP_always)
6746 Bits |= OMP_MAP_ALWAYS;
6747 return Bits;
6748 }
6749
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006750 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006751 /// final array section, is one whose length can't be proved to be one.
6752 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006753 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006754
6755 // It is not an array section and therefore not a unity-size one.
6756 if (!OASE)
6757 return false;
6758
6759 // An array section with no colon always refer to a single element.
6760 if (OASE->getColonLoc().isInvalid())
6761 return false;
6762
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006763 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006764
6765 // If we don't have a length we have to check if the array has size 1
6766 // for this dimension. Also, we should always expect a length if the
6767 // base type is pointer.
6768 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006769 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6770 OASE->getBase()->IgnoreParenImpCasts())
6771 .getCanonicalType();
6772 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006773 return ATy->getSize().getSExtValue() != 1;
6774 // If we don't have a constant dimension length, we have to consider
6775 // the current section as having any size, so it is not necessarily
6776 // unitary. If it happen to be unity size, that's user fault.
6777 return true;
6778 }
6779
6780 // Check if the length evaluates to 1.
6781 llvm::APSInt ConstLength;
6782 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6783 return true; // Can have more that size 1.
6784
6785 return ConstLength.getSExtValue() != 1;
6786 }
6787
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006788 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006789 /// bits for the provided map type, map modifier, and expression components.
6790 /// \a IsFirstComponent should be set to true if the provided set of
6791 /// components is the first associated with a capture.
6792 void generateInfoForComponentList(
6793 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6794 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006795 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006796 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006797 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006798 bool IsImplicit,
6799 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6800 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006801 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006802 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006803 // base pointer, section pointer, size, flags
6804 // (to add to the ones that come from the map type and modifier).
6805 //
6806 // double d;
6807 // int i[100];
6808 // float *p;
6809 //
6810 // struct S1 {
6811 // int i;
6812 // float f[50];
6813 // }
6814 // struct S2 {
6815 // int i;
6816 // float f[50];
6817 // S1 s;
6818 // double *p;
6819 // struct S2 *ps;
6820 // }
6821 // S2 s;
6822 // S2 *ps;
6823 //
6824 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006825 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006826 //
6827 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006828 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006829 //
6830 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006831 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006832 //
6833 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006834 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006835 //
6836 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006837 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006838 //
6839 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006840 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006841 //
6842 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006843 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006844 //
6845 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006846 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006847 //
6848 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006849 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006850 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006851 // map(to: s.p[:22])
6852 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6853 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6854 // &(s.p), &(s.p[0]), 22*sizeof(double),
6855 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6856 // (*) alloc space for struct members, only this is a target parameter
6857 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6858 // optimizes this entry out, same in the examples below)
6859 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006860 //
6861 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006862 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006863 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006864 // map(from: s.ps->s.i)
6865 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6866 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6867 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006868 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006869 // map(to: s.ps->ps)
6870 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6871 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6872 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006873 //
6874 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006875 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6876 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6877 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6878 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006879 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006880 // map(to: s.ps->ps->s.f[:22])
6881 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6882 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6883 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6884 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006885 //
6886 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006887 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006888 //
6889 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006890 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006891 //
6892 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006893 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006894 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006895 // map(from: ps->p)
6896 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006897 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006898 // map(to: ps->p[:22])
6899 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6900 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6901 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006902 //
6903 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006904 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006905 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006906 // map(from: ps->ps->s.i)
6907 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6908 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6909 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006910 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006911 // map(from: ps->ps->ps)
6912 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6913 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6914 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006915 //
6916 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006917 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6918 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6919 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6920 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006921 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006922 // map(to: ps->ps->ps->s.f[:22])
6923 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6924 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6925 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6926 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6927 //
6928 // map(to: s.f[:22]) map(from: s.p[:33])
6929 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
6930 // sizeof(double*) (**), TARGET_PARAM
6931 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
6932 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
6933 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
6934 // (*) allocate contiguous space needed to fit all mapped members even if
6935 // we allocate space for members not mapped (in this example,
6936 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
6937 // them as well because they fall between &s.f[0] and &s.p)
6938 //
6939 // map(from: s.f[:22]) map(to: ps->p[:33])
6940 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
6941 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6942 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
6943 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
6944 // (*) the struct this entry pertains to is the 2nd element in the list of
6945 // arguments, hence MEMBER_OF(2)
6946 //
6947 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
6948 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
6949 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
6950 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
6951 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6952 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
6953 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
6954 // (*) the struct this entry pertains to is the 4th element in the list
6955 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00006956
6957 // Track if the map information being generated is the first for a capture.
6958 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006959 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006960
6961 // Scan the components from the base to the complete expression.
6962 auto CI = Components.rbegin();
6963 auto CE = Components.rend();
6964 auto I = CI;
6965
6966 // Track if the map information being generated is the first for a list of
6967 // components.
6968 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006969 Address BP = Address::invalid();
Samuel Antao86ace552016-04-27 22:40:57 +00006970
Erich Keanee69755a2018-07-19 17:19:16 +00006971 if (isa<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006972 // The base is the 'this' pointer. The content of the pointer is going
6973 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00006974 BP = CGF.LoadCXXThisAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00006975 } else {
6976 // The base is the reference to the variable.
6977 // BP = &Var.
Alexey Bataevb3638132018-07-19 16:34:13 +00006978 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00006979 if (const auto *VD =
6980 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6981 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00006982 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006983 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
6984 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006985 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006986 }
Alexey Bataev92327c52018-03-26 16:40:55 +00006987 }
Samuel Antao86ace552016-04-27 22:40:57 +00006988
6989 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006990 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006991 // reference. References are ignored for mapping purposes.
6992 QualType Ty =
6993 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6994 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00006995 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00006996
6997 // We do not need to generate individual map information for the
6998 // pointer, it can be associated with the combined storage.
6999 ++I;
7000 }
7001 }
7002
Alexey Bataevb3638132018-07-19 16:34:13 +00007003 // Track whether a component of the list should be marked as MEMBER_OF some
7004 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7005 // in a component list should be marked as MEMBER_OF, all subsequent entries
7006 // do not belong to the base struct. E.g.
7007 // struct S2 s;
7008 // s.ps->ps->ps->f[:]
7009 // (1) (2) (3) (4)
7010 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7011 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7012 // is the pointee of ps(2) which is not member of struct s, so it should not
7013 // be marked as such (it is still PTR_AND_OBJ).
7014 // The variable is initialized to false so that PTR_AND_OBJ entries which
7015 // are not struct members are not considered (e.g. array of pointers to
7016 // data).
7017 bool ShouldBeMemberOf = false;
7018
7019 // Variable keeping track of whether or not we have encountered a component
7020 // in the component list which is a member expression. Useful when we have a
7021 // pointer or a final array section, in which case it is the previous
7022 // component in the list which tells us whether we have a member expression.
7023 // E.g. X.f[:]
7024 // While processing the final array section "[:]" it is "f" which tells us
7025 // whether we are dealing with a member of a declared struct.
7026 const MemberExpr *EncounteredME = nullptr;
7027
Samuel Antao86ace552016-04-27 22:40:57 +00007028 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007029 // If the current component is member of a struct (parent struct) mark it.
7030 if (!EncounteredME) {
7031 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
7032 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
7033 // as MEMBER_OF the parent struct.
7034 if (EncounteredME)
7035 ShouldBeMemberOf = true;
7036 }
7037
Samuel Antao86ace552016-04-27 22:40:57 +00007038 auto Next = std::next(I);
7039
7040 // We need to generate the addresses and sizes if this is the last
7041 // component, if the component is a pointer or if it is an array section
7042 // whose length can't be proved to be one. If this is a pointer, it
7043 // becomes the base address for the following components.
7044
7045 // A final array section, is one whose length can't be proved to be one.
7046 bool IsFinalArraySection =
7047 isFinalArraySectionExpression(I->getAssociatedExpression());
7048
7049 // Get information on whether the element is a pointer. Have to do a
7050 // special treatment for array sections given that they are built-in
7051 // types.
7052 const auto *OASE =
7053 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7054 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007055 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7056 .getCanonicalType()
7057 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007058 I->getAssociatedExpression()->getType()->isAnyPointerType();
7059
7060 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007061 // If this is not the last component, we expect the pointer to be
7062 // associated with an array expression or member expression.
7063 assert((Next == CE ||
7064 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7065 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7066 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7067 "Unexpected expression");
7068
Alexey Bataevb3638132018-07-19 16:34:13 +00007069 Address LB =
7070 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007071
Alexey Bataevb3638132018-07-19 16:34:13 +00007072 // If this component is a pointer inside the base struct then we don't
7073 // need to create any entry for it - it will be combined with the object
7074 // it is pointing to into a single PTR_AND_OBJ entry.
7075 bool IsMemberPointer =
7076 IsPointer && EncounteredME &&
7077 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7078 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007079 if (!OverlappedElements.empty()) {
7080 // Handle base element with the info for overlapped elements.
7081 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7082 assert(Next == CE &&
7083 "Expected last element for the overlapped elements.");
7084 assert(!IsPointer &&
7085 "Unexpected base element with the pointer type.");
7086 // Mark the whole struct as the struct that requires allocation on the
7087 // device.
7088 PartialStruct.LowestElem = {0, LB};
7089 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7090 I->getAssociatedExpression()->getType());
7091 Address HB = CGF.Builder.CreateConstGEP(
7092 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7093 CGF.VoidPtrTy),
7094 TypeSize.getQuantity() - 1, CharUnits::One());
7095 PartialStruct.HighestElem = {
7096 std::numeric_limits<decltype(
7097 PartialStruct.HighestElem.first)>::max(),
7098 HB};
7099 PartialStruct.Base = BP;
7100 // Emit data for non-overlapped data.
7101 OpenMPOffloadMappingFlags Flags =
7102 OMP_MAP_MEMBER_OF |
7103 getMapTypeBits(MapType, MapTypeModifier, IsImplicit,
7104 /*AddPtrFlag=*/false,
7105 /*AddIsTargetParamFlag=*/false);
7106 LB = BP;
7107 llvm::Value *Size = nullptr;
7108 // Do bitcopy of all non-overlapped structure elements.
7109 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7110 Component : OverlappedElements) {
7111 Address ComponentLB = Address::invalid();
7112 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7113 Component) {
7114 if (MC.getAssociatedDeclaration()) {
7115 ComponentLB =
7116 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7117 .getAddress();
7118 Size = CGF.Builder.CreatePtrDiff(
7119 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7120 CGF.EmitCastToVoidPtr(LB.getPointer()));
7121 break;
7122 }
7123 }
7124 BasePointers.push_back(BP.getPointer());
7125 Pointers.push_back(LB.getPointer());
7126 Sizes.push_back(Size);
7127 Types.push_back(Flags);
7128 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1,
7129 CGF.getPointerSize());
7130 }
7131 BasePointers.push_back(BP.getPointer());
7132 Pointers.push_back(LB.getPointer());
7133 Size = CGF.Builder.CreatePtrDiff(
7134 CGF.EmitCastToVoidPtr(
7135 CGF.Builder.CreateConstGEP(HB, 1, CharUnits::One())
7136 .getPointer()),
7137 CGF.EmitCastToVoidPtr(LB.getPointer()));
7138 Sizes.push_back(Size);
7139 Types.push_back(Flags);
7140 break;
7141 }
7142 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007143 if (!IsMemberPointer) {
7144 BasePointers.push_back(BP.getPointer());
7145 Pointers.push_back(LB.getPointer());
7146 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007147
Alexey Bataevb3638132018-07-19 16:34:13 +00007148 // We need to add a pointer flag for each map that comes from the
7149 // same expression except for the first one. We also need to signal
7150 // this map is the first one that relates with the current capture
7151 // (there is a set of entries for each capture).
7152 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
7153 MapType, MapTypeModifier, IsImplicit,
7154 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7155
7156 if (!IsExpressionFirstInfo) {
7157 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7158 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7159 if (IsPointer)
7160 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7161 OMP_MAP_DELETE);
7162
7163 if (ShouldBeMemberOf) {
7164 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7165 // should be later updated with the correct value of MEMBER_OF.
7166 Flags |= OMP_MAP_MEMBER_OF;
7167 // From now on, all subsequent PTR_AND_OBJ entries should not be
7168 // marked as MEMBER_OF.
7169 ShouldBeMemberOf = false;
7170 }
7171 }
7172
7173 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007174 }
7175
Alexey Bataevb3638132018-07-19 16:34:13 +00007176 // If we have encountered a member expression so far, keep track of the
7177 // mapped member. If the parent is "*this", then the value declaration
7178 // is nullptr.
7179 if (EncounteredME) {
7180 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7181 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007182
Alexey Bataevb3638132018-07-19 16:34:13 +00007183 // Update info about the lowest and highest elements for this struct
7184 if (!PartialStruct.Base.isValid()) {
7185 PartialStruct.LowestElem = {FieldIndex, LB};
7186 PartialStruct.HighestElem = {FieldIndex, LB};
7187 PartialStruct.Base = BP;
7188 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7189 PartialStruct.LowestElem = {FieldIndex, LB};
7190 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7191 PartialStruct.HighestElem = {FieldIndex, LB};
7192 }
7193 }
Samuel Antao86ace552016-04-27 22:40:57 +00007194
7195 // If we have a final array section, we are done with this expression.
7196 if (IsFinalArraySection)
7197 break;
7198
7199 // The pointer becomes the base for the next element.
7200 if (Next != CE)
7201 BP = LB;
7202
7203 IsExpressionFirstInfo = false;
7204 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007205 }
7206 }
7207 }
7208
Alexey Bataevb3638132018-07-19 16:34:13 +00007209 /// Return the adjusted map modifiers if the declaration a capture refers to
7210 /// appears in a first-private clause. This is expected to be used only with
7211 /// directives that start with 'target'.
7212 MappableExprsHandler::OpenMPOffloadMappingFlags
7213 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7214 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7215
7216 // A first private variable captured by reference will use only the
7217 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7218 // declaration is known as first-private in this handler.
7219 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
7220 return MappableExprsHandler::OMP_MAP_PRIVATE |
7221 MappableExprsHandler::OMP_MAP_TO;
7222 return MappableExprsHandler::OMP_MAP_TO |
7223 MappableExprsHandler::OMP_MAP_FROM;
7224 }
7225
7226 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7227 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7228 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7229 << 48);
7230 }
7231
7232 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7233 OpenMPOffloadMappingFlags MemberOfFlag) {
7234 // If the entry is PTR_AND_OBJ but has not been marked with the special
7235 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7236 // marked as MEMBER_OF.
7237 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7238 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7239 return;
7240
7241 // Reset the placeholder value to prepare the flag for the assignment of the
7242 // proper MEMBER_OF value.
7243 Flags &= ~OMP_MAP_MEMBER_OF;
7244 Flags |= MemberOfFlag;
7245 }
7246
Alexey Bataeve82445f2018-09-20 13:54:02 +00007247 void getPlainLayout(const CXXRecordDecl *RD,
7248 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7249 bool AsBase) const {
7250 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7251
7252 llvm::StructType *St =
7253 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7254
7255 unsigned NumElements = St->getNumElements();
7256 llvm::SmallVector<
7257 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7258 RecordLayout(NumElements);
7259
7260 // Fill bases.
7261 for (const auto &I : RD->bases()) {
7262 if (I.isVirtual())
7263 continue;
7264 const auto *Base = I.getType()->getAsCXXRecordDecl();
7265 // Ignore empty bases.
7266 if (Base->isEmpty() || CGF.getContext()
7267 .getASTRecordLayout(Base)
7268 .getNonVirtualSize()
7269 .isZero())
7270 continue;
7271
7272 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7273 RecordLayout[FieldIndex] = Base;
7274 }
7275 // Fill in virtual bases.
7276 for (const auto &I : RD->vbases()) {
7277 const auto *Base = I.getType()->getAsCXXRecordDecl();
7278 // Ignore empty bases.
7279 if (Base->isEmpty())
7280 continue;
7281 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7282 if (RecordLayout[FieldIndex])
7283 continue;
7284 RecordLayout[FieldIndex] = Base;
7285 }
7286 // Fill in all the fields.
7287 assert(!RD->isUnion() && "Unexpected union.");
7288 for (const auto *Field : RD->fields()) {
7289 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7290 // will fill in later.)
7291 if (!Field->isBitField()) {
7292 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7293 RecordLayout[FieldIndex] = Field;
7294 }
7295 }
7296 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7297 &Data : RecordLayout) {
7298 if (Data.isNull())
7299 continue;
7300 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7301 getPlainLayout(Base, Layout, /*AsBase=*/true);
7302 else
7303 Layout.push_back(Data.get<const FieldDecl *>());
7304 }
7305 }
7306
Alexey Bataevb3638132018-07-19 16:34:13 +00007307public:
7308 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7309 : CurDir(Dir), CGF(CGF) {
7310 // Extract firstprivate clause information.
7311 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7312 for (const auto *D : C->varlists())
7313 FirstPrivateDecls.insert(
7314 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7315 // Extract device pointer clause information.
7316 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7317 for (auto L : C->component_lists())
7318 DevPointersMap[L.first].push_back(L.second);
7319 }
7320
7321 /// Generate code for the combined entry if we have a partially mapped struct
7322 /// and take care of the mapping flags of the arguments corresponding to
7323 /// individual struct members.
7324 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7325 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7326 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7327 const StructRangeInfoTy &PartialStruct) const {
7328 // Base is the base of the struct
7329 BasePointers.push_back(PartialStruct.Base.getPointer());
7330 // Pointer is the address of the lowest element
7331 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7332 Pointers.push_back(LB);
7333 // Size is (addr of {highest+1} element) - (addr of lowest element)
7334 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7335 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7336 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7337 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7338 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7339 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7340 /*isSinged=*/false);
7341 Sizes.push_back(Size);
7342 // Map type is always TARGET_PARAM
7343 Types.push_back(OMP_MAP_TARGET_PARAM);
7344 // Remove TARGET_PARAM flag from the first element
7345 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7346
7347 // All other current entries will be MEMBER_OF the combined entry
7348 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7349 // 0xFFFF in the MEMBER_OF field).
7350 OpenMPOffloadMappingFlags MemberOfFlag =
7351 getMemberOfFlag(BasePointers.size() - 1);
7352 for (auto &M : CurTypes)
7353 setCorrectMemberOfFlag(M, MemberOfFlag);
7354 }
7355
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007356 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007357 /// types for the extracted mappable expressions. Also, for each item that
7358 /// relates with a device pointer, a pair of the relevant declaration and
7359 /// index where it occurs is appended to the device pointers info array.
7360 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007361 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7362 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007363 // We have to process the component lists that relate with the same
7364 // declaration in a single chunk so that we can generate the map flags
7365 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007366 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007367
7368 // Helper function to fill the information map for the different supported
7369 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007370 auto &&InfoGen = [&Info](
7371 const ValueDecl *D,
7372 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7373 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevb3638132018-07-19 16:34:13 +00007374 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007375 const ValueDecl *VD =
7376 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007377 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7378 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007379 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007380
Paul Robinson78fb1322016-08-01 22:12:46 +00007381 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007382 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7383 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007384 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007385 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007386 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007387 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7388 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007389 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007390 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007391 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007392 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7393 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007394 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007395 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007396 }
Samuel Antao86ace552016-04-27 22:40:57 +00007397
Samuel Antaocc10b852016-07-28 14:23:26 +00007398 // Look at the use_device_ptr clause information and mark the existing map
7399 // entries as such. If there is no map information for an entry in the
7400 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007401 // section. It is the user fault if that was not mapped before. If there is
7402 // no map information and the pointer is a struct member, then we defer the
7403 // emission of that entry until the whole struct has been processed.
7404 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7405 DeferredInfo;
7406
Paul Robinson78fb1322016-08-01 22:12:46 +00007407 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007408 for (const auto *C :
7409 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007410 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007411 assert(!L.second.empty() && "Not expecting empty list of components!");
7412 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7413 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007414 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007415 // If the first component is a member expression, we have to look into
7416 // 'this', which maps to null in the map of map information. Otherwise
7417 // look directly for the information.
7418 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7419
7420 // We potentially have map information for this declaration already.
7421 // Look for the first set of components that refer to it.
7422 if (It != Info.end()) {
7423 auto CI = std::find_if(
7424 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7425 return MI.Components.back().getAssociatedDeclaration() == VD;
7426 });
7427 // If we found a map entry, signal that the pointer has to be returned
7428 // and move on to the next declaration.
7429 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007430 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007431 continue;
7432 }
7433 }
7434
7435 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007436 // size array section - if the pointer is a struct member we defer this
7437 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007438 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007439 if (isa<MemberExpr>(IE)) {
7440 // Insert the pointer into Info to be processed by
7441 // generateInfoForComponentList. Because it is a member pointer
7442 // without a pointee, no entry will be generated for it, therefore
7443 // we need to generate one after the whole struct has been processed.
7444 // Nonetheless, generateInfoForComponentList must be called to take
7445 // the pointer into account for the calculation of the range of the
7446 // partial struct.
7447 InfoGen(nullptr, L.second, OMPC_MAP_unknown, OMPC_MAP_unknown,
7448 /*ReturnDevicePointer=*/false, C->isImplicit());
7449 DeferredInfo[nullptr].emplace_back(IE, VD);
7450 } else {
7451 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7452 this->CGF.EmitLValue(IE), IE->getExprLoc());
7453 BasePointers.emplace_back(Ptr, VD);
7454 Pointers.push_back(Ptr);
7455 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7456 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7457 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007458 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007459 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007460
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007461 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007462 // We need to know when we generate information for the first component
7463 // associated with a capture, because the mapping flags depend on it.
7464 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007465
7466 // Temporary versions of arrays
7467 MapBaseValuesArrayTy CurBasePointers;
7468 MapValuesArrayTy CurPointers;
7469 MapValuesArrayTy CurSizes;
7470 MapFlagsArrayTy CurTypes;
7471 StructRangeInfoTy PartialStruct;
7472
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007473 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007474 assert(!L.Components.empty() &&
7475 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007476
7477 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007478 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007479 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007480 this->generateInfoForComponentList(
Alexey Bataevb3638132018-07-19 16:34:13 +00007481 L.MapType, L.MapTypeModifier, L.Components, CurBasePointers,
7482 CurPointers, CurSizes, CurTypes, PartialStruct,
7483 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007484
7485 // If this entry relates with a device pointer, set the relevant
7486 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007487 if (L.ReturnDevicePointer) {
7488 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007489 "Unexpected number of mapped base pointers.");
7490
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007491 const ValueDecl *RelevantVD =
7492 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007493 assert(RelevantVD &&
7494 "No relevant declaration related with device pointer??");
7495
Alexey Bataevb3638132018-07-19 16:34:13 +00007496 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7497 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007498 }
Samuel Antao86ace552016-04-27 22:40:57 +00007499 IsFirstComponentList = false;
7500 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007501
7502 // Append any pending zero-length pointers which are struct members and
7503 // used with use_device_ptr.
7504 auto CI = DeferredInfo.find(M.first);
7505 if (CI != DeferredInfo.end()) {
7506 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7507 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7508 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7509 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7510 CurBasePointers.emplace_back(BasePtr, L.VD);
7511 CurPointers.push_back(Ptr);
7512 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7513 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7514 // value MEMBER_OF=FFFF so that the entry is later updated with the
7515 // correct value of MEMBER_OF.
7516 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7517 OMP_MAP_MEMBER_OF);
7518 }
7519 }
7520
7521 // If there is an entry in PartialStruct it means we have a struct with
7522 // individual members mapped. Emit an extra combined entry.
7523 if (PartialStruct.Base.isValid())
7524 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7525 PartialStruct);
7526
7527 // We need to append the results of this capture to what we already have.
7528 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7529 Pointers.append(CurPointers.begin(), CurPointers.end());
7530 Sizes.append(CurSizes.begin(), CurSizes.end());
7531 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007532 }
7533 }
7534
Alexey Bataev60705422018-10-30 15:50:12 +00007535 /// Emit capture info for lambdas for variables captured by reference.
7536 void generateInfoForLambdaCaptures(const ValueDecl *VD, llvm::Value *Arg,
7537 MapBaseValuesArrayTy &BasePointers,
7538 MapValuesArrayTy &Pointers,
7539 MapValuesArrayTy &Sizes,
7540 MapFlagsArrayTy &Types) const {
7541 const auto *RD = VD->getType()
7542 .getCanonicalType()
7543 .getNonReferenceType()
7544 ->getAsCXXRecordDecl();
7545 if (!RD || !RD->isLambda())
7546 return;
7547 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
7548 LValue VDLVal = CGF.MakeAddrLValue(
7549 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
7550 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
7551 FieldDecl *ThisCapture = nullptr;
7552 RD->getCaptureFields(Captures, ThisCapture);
7553 if (ThisCapture) {
7554 LValue ThisLVal =
7555 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
7556 BasePointers.push_back(VDLVal.getPointer());
7557 Pointers.push_back(ThisLVal.getPointer());
7558 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007559 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007560 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7561 }
7562 for (const LambdaCapture &LC : RD->captures()) {
7563 if (LC.getCaptureKind() != LCK_ByRef)
7564 continue;
7565 const VarDecl *VD = LC.getCapturedVar();
7566 auto It = Captures.find(VD);
7567 assert(It != Captures.end() && "Found lambda capture without field.");
7568 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
7569 BasePointers.push_back(VDLVal.getPointer());
7570 Pointers.push_back(VarLVal.getPointer());
7571 Sizes.push_back(CGF.getTypeSize(
7572 VD->getType().getCanonicalType().getNonReferenceType()));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007573 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007574 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7575 }
7576 }
7577
7578 /// Set correct indices for lambdas captures.
7579 void adjustMemberOfForLambdaCaptures(MapBaseValuesArrayTy &BasePointers,
7580 MapValuesArrayTy &Pointers,
7581 MapFlagsArrayTy &Types) const {
7582 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
7583 // Set correct member_of idx for all implicit lambda captures.
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007584 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007585 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
7586 continue;
7587 llvm::Value *BasePtr = *BasePointers[I];
7588 int TgtIdx = -1;
7589 for (unsigned J = I; J > 0; --J) {
7590 unsigned Idx = J - 1;
7591 if (Pointers[Idx] != BasePtr)
7592 continue;
7593 TgtIdx = Idx;
7594 break;
7595 }
7596 assert(TgtIdx != -1 && "Unable to find parent lambda.");
7597 // All other current entries will be MEMBER_OF the combined entry
7598 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7599 // 0xFFFF in the MEMBER_OF field).
7600 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
7601 setCorrectMemberOfFlag(Types[I], MemberOfFlag);
7602 }
7603 }
7604
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007605 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007606 /// associated to a given capture.
7607 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007608 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007609 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007610 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007611 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7612 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007613 assert(!Cap->capturesVariableArrayType() &&
7614 "Not expecting to generate map info for a variable array type!");
7615
Samuel Antao6890b092016-07-28 14:25:09 +00007616 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007617 const ValueDecl *VD = Cap->capturesThis()
7618 ? nullptr
7619 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007620
Samuel Antao6890b092016-07-28 14:25:09 +00007621 // If this declaration appears in a is_device_ptr clause we just have to
7622 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007623 // pass its value.
7624 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007625 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007626 Pointers.push_back(Arg);
7627 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007628 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007629 return;
7630 }
7631
Alexey Bataeve82445f2018-09-20 13:54:02 +00007632 using MapData =
7633 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
7634 OpenMPMapClauseKind, OpenMPMapClauseKind, bool>;
7635 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007636 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007637 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007638 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007639 assert(L.first == VD &&
7640 "We got information for the wrong declaration??");
7641 assert(!L.second.empty() &&
7642 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007643 DeclComponentLists.emplace_back(L.second, C->getMapType(),
7644 C->getMapTypeModifier(),
7645 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007646 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007647 }
7648
7649 // Find overlapping elements (including the offset from the base element).
7650 llvm::SmallDenseMap<
7651 const MapData *,
7652 llvm::SmallVector<
7653 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7654 4>
7655 OverlappedData;
7656 size_t Count = 0;
7657 for (const MapData &L : DeclComponentLists) {
7658 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7659 OpenMPMapClauseKind MapType;
7660 OpenMPMapClauseKind MapTypeModifier;
7661 bool IsImplicit;
7662 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7663 ++Count;
7664 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7665 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
7666 std::tie(Components1, MapType, MapTypeModifier, IsImplicit) = L1;
7667 auto CI = Components.rbegin();
7668 auto CE = Components.rend();
7669 auto SI = Components1.rbegin();
7670 auto SE = Components1.rend();
7671 for (; CI != CE && SI != SE; ++CI, ++SI) {
7672 if (CI->getAssociatedExpression()->getStmtClass() !=
7673 SI->getAssociatedExpression()->getStmtClass())
7674 break;
7675 // Are we dealing with different variables/fields?
7676 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7677 break;
7678 }
7679 // Found overlapping if, at least for one component, reached the head of
7680 // the components list.
7681 if (CI == CE || SI == SE) {
7682 assert((CI != CE || SI != SE) &&
7683 "Unexpected full match of the mapping components.");
7684 const MapData &BaseData = CI == CE ? L : L1;
7685 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7686 SI == SE ? Components : Components1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007687 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7688 OverlappedElements.getSecond().push_back(SubData);
7689 }
7690 }
7691 }
7692 // Sort the overlapped elements for each item.
7693 llvm::SmallVector<const FieldDecl *, 4> Layout;
7694 if (!OverlappedData.empty()) {
7695 if (const auto *CRD =
7696 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7697 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7698 else {
7699 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7700 Layout.append(RD->field_begin(), RD->field_end());
7701 }
7702 }
7703 for (auto &Pair : OverlappedData) {
7704 llvm::sort(
7705 Pair.getSecond(),
7706 [&Layout](
7707 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7708 OMPClauseMappableExprCommon::MappableExprComponentListRef
7709 Second) {
7710 auto CI = First.rbegin();
7711 auto CE = First.rend();
7712 auto SI = Second.rbegin();
7713 auto SE = Second.rend();
7714 for (; CI != CE && SI != SE; ++CI, ++SI) {
7715 if (CI->getAssociatedExpression()->getStmtClass() !=
7716 SI->getAssociatedExpression()->getStmtClass())
7717 break;
7718 // Are we dealing with different variables/fields?
7719 if (CI->getAssociatedDeclaration() !=
7720 SI->getAssociatedDeclaration())
7721 break;
7722 }
Richard Trieu5061e832018-09-21 21:20:33 +00007723
7724 // Lists contain the same elements.
7725 if (CI == CE && SI == SE)
7726 return false;
7727
7728 // List with less elements is less than list with more elements.
7729 if (CI == CE || SI == SE)
7730 return CI == CE;
7731
Alexey Bataeve82445f2018-09-20 13:54:02 +00007732 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7733 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7734 if (FD1->getParent() == FD2->getParent())
7735 return FD1->getFieldIndex() < FD2->getFieldIndex();
7736 const auto It =
7737 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7738 return FD == FD1 || FD == FD2;
7739 });
7740 return *It == FD1;
7741 });
7742 }
7743
7744 // Associated with a capture, because the mapping flags depend on it.
7745 // Go through all of the elements with the overlapped elements.
7746 for (const auto &Pair : OverlappedData) {
7747 const MapData &L = *Pair.getFirst();
7748 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7749 OpenMPMapClauseKind MapType;
7750 OpenMPMapClauseKind MapTypeModifier;
7751 bool IsImplicit;
7752 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7753 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7754 OverlappedComponents = Pair.getSecond();
7755 bool IsFirstComponentList = true;
7756 generateInfoForComponentList(MapType, MapTypeModifier, Components,
7757 BasePointers, Pointers, Sizes, Types,
7758 PartialStruct, IsFirstComponentList,
7759 IsImplicit, OverlappedComponents);
7760 }
7761 // Go through other elements without overlapped elements.
7762 bool IsFirstComponentList = OverlappedData.empty();
7763 for (const MapData &L : DeclComponentLists) {
7764 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7765 OpenMPMapClauseKind MapType;
7766 OpenMPMapClauseKind MapTypeModifier;
7767 bool IsImplicit;
7768 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7769 auto It = OverlappedData.find(&L);
7770 if (It == OverlappedData.end())
7771 generateInfoForComponentList(MapType, MapTypeModifier, Components,
7772 BasePointers, Pointers, Sizes, Types,
7773 PartialStruct, IsFirstComponentList,
7774 IsImplicit);
7775 IsFirstComponentList = false;
7776 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007777 }
Samuel Antao86ace552016-04-27 22:40:57 +00007778
Alexey Bataevb3638132018-07-19 16:34:13 +00007779 /// Generate the base pointers, section pointers, sizes and map types
7780 /// associated with the declare target link variables.
7781 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7782 MapValuesArrayTy &Pointers,
7783 MapValuesArrayTy &Sizes,
7784 MapFlagsArrayTy &Types) const {
7785 // Map other list items in the map clause which are not captured variables
7786 // but "declare target link" global variables.,
7787 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7788 for (const auto &L : C->component_lists()) {
7789 if (!L.first)
7790 continue;
7791 const auto *VD = dyn_cast<VarDecl>(L.first);
7792 if (!VD)
7793 continue;
7794 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007795 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007796 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7797 continue;
7798 StructRangeInfoTy PartialStruct;
7799 generateInfoForComponentList(
7800 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7801 Pointers, Sizes, Types, PartialStruct,
7802 /*IsFirstComponentList=*/true, C->isImplicit());
7803 assert(!PartialStruct.Base.isValid() &&
7804 "No partial structs for declare target link expected.");
7805 }
7806 }
Samuel Antao86ace552016-04-27 22:40:57 +00007807 }
Samuel Antaod486f842016-05-26 16:53:38 +00007808
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007809 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007810 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007811 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7812 const FieldDecl &RI, llvm::Value *CV,
7813 MapBaseValuesArrayTy &CurBasePointers,
7814 MapValuesArrayTy &CurPointers,
7815 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007816 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007817 // Do the default mapping.
7818 if (CI.capturesThis()) {
7819 CurBasePointers.push_back(CV);
7820 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007821 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007822 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7823 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007824 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007825 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007826 CurBasePointers.push_back(CV);
7827 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007828 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007829 // We have to signal to the runtime captures passed by value that are
7830 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007831 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007832 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7833 } else {
7834 // Pointers are implicitly mapped with a zero size and no flags
7835 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007836 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007837 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7838 }
7839 } else {
7840 assert(CI.capturesVariable() && "Expected captured reference.");
7841 CurBasePointers.push_back(CV);
7842 CurPointers.push_back(CV);
7843
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007844 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007845 QualType ElementType = PtrTy->getPointeeType();
7846 CurSizes.push_back(CGF.getTypeSize(ElementType));
7847 // The default map type for a scalar/complex type is 'to' because by
7848 // default the value doesn't have to be retrieved. For an aggregate
7849 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007850 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Samuel Antaod486f842016-05-26 16:53:38 +00007851 }
George Rokos065755d2017-11-07 18:27:04 +00007852 // Every default map produces a single argument which is a target parameter.
7853 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007854
7855 // Add flag stating this is an implicit map.
7856 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007857 }
Samuel Antao86ace552016-04-27 22:40:57 +00007858};
Samuel Antaodf158d52016-04-27 22:58:19 +00007859
7860enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007861 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007862 /// from environment variables in the spec.
7863 OMP_DEVICEID_UNDEF = -1,
7864};
7865} // anonymous namespace
7866
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007867/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007868/// offloading runtime library. If there is no map or capture information,
7869/// return nullptr by reference.
7870static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007871emitOffloadingArrays(CodeGenFunction &CGF,
7872 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007873 MappableExprsHandler::MapValuesArrayTy &Pointers,
7874 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007875 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7876 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007877 CodeGenModule &CGM = CGF.CGM;
7878 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007879
Samuel Antaocc10b852016-07-28 14:23:26 +00007880 // Reset the array information.
7881 Info.clearArrayInfo();
7882 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007883
Samuel Antaocc10b852016-07-28 14:23:26 +00007884 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007885 // Detect if we have any capture size requiring runtime evaluation of the
7886 // size so that a constant array could be eventually used.
7887 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007888 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007889 if (!isa<llvm::Constant>(S)) {
7890 hasRuntimeEvaluationCaptureSize = true;
7891 break;
7892 }
7893
Samuel Antaocc10b852016-07-28 14:23:26 +00007894 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007895 QualType PointerArrayType =
7896 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7897 /*IndexTypeQuals=*/0);
7898
Samuel Antaocc10b852016-07-28 14:23:26 +00007899 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007900 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007901 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007902 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7903
7904 // If we don't have any VLA types or other types that require runtime
7905 // evaluation, we can use a constant array for the map sizes, otherwise we
7906 // need to fill up the arrays as we do for the pointers.
7907 if (hasRuntimeEvaluationCaptureSize) {
7908 QualType SizeArrayType = Ctx.getConstantArrayType(
7909 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7910 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007911 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007912 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7913 } else {
7914 // We expect all the sizes to be constant, so we collect them to create
7915 // a constant array.
7916 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007917 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007918 ConstSizes.push_back(cast<llvm::Constant>(S));
7919
7920 auto *SizesArrayInit = llvm::ConstantArray::get(
7921 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007922 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007923 auto *SizesArrayGbl = new llvm::GlobalVariable(
7924 CGM.getModule(), SizesArrayInit->getType(),
7925 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007926 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007927 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007928 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007929 }
7930
7931 // The map types are always constant so we don't need to generate code to
7932 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00007933 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
7934 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00007935 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00007936 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007937 std::string MaptypesName =
7938 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007939 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7940 CGM.getModule(), MapTypesArrayInit->getType(),
7941 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007942 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007943 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007944 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007945
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007946 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7947 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007948 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007949 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007950 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007951 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7952 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007953 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7954 CGF.Builder.CreateStore(BPVal, BPAddr);
7955
Samuel Antaocc10b852016-07-28 14:23:26 +00007956 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007957 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007958 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007959
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007960 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007961 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007962 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007963 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007964 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7965 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007966 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7967 CGF.Builder.CreateStore(PVal, PAddr);
7968
7969 if (hasRuntimeEvaluationCaptureSize) {
7970 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007971 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7972 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007973 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007974 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00007975 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7976 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007977 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00007978 SAddr);
7979 }
7980 }
7981 }
7982}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007983/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00007984/// arrays of pointers, sizes and map types.
7985static void emitOffloadingArraysArgument(
7986 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7987 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007988 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007989 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007990 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007991 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007992 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7993 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007994 /*Idx0=*/0, /*Idx1=*/0);
7995 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007996 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7997 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007998 /*Idx0=*/0,
7999 /*Idx1=*/0);
8000 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008001 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008002 /*Idx0=*/0, /*Idx1=*/0);
8003 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00008004 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00008005 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008006 /*Idx0=*/0,
8007 /*Idx1=*/0);
8008 } else {
8009 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8010 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8011 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
8012 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00008013 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00008014 }
Samuel Antao86ace552016-04-27 22:40:57 +00008015}
8016
Samuel Antaobed3c462015-10-02 16:14:20 +00008017void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
8018 const OMPExecutableDirective &D,
8019 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00008020 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008021 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00008022 if (!CGF.HaveInsertPoint())
8023 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00008024
Samuel Antaoee8fb302016-01-06 13:42:12 +00008025 assert(OutlinedFn && "Invalid outlined function!");
8026
Alexey Bataev8451efa2018-01-15 19:06:12 +00008027 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
8028 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00008029 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008030 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
8031 PrePostActionTy &) {
8032 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8033 };
8034 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00008035
Alexey Bataev8451efa2018-01-15 19:06:12 +00008036 CodeGenFunction::OMPTargetDataInfo InputInfo;
8037 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00008038 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008039 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
8040 &MapTypesArray, &CS, RequiresOuterTask,
8041 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008042 // On top of the arrays that were filled up, the target offloading call
8043 // takes as arguments the device id as well as the host pointer. The host
8044 // pointer is used by the runtime library to identify the current target
8045 // region, so it only has to be unique and not necessarily point to
8046 // anything. It could be the pointer to the outlined function that
8047 // implements the target region, but we aren't using that so that the
8048 // compiler doesn't need to keep that, and could therefore inline the host
8049 // function if proven worthwhile during optimization.
8050
Samuel Antaoee8fb302016-01-06 13:42:12 +00008051 // From this point on, we need to have an ID of the target region defined.
8052 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00008053
8054 // Emit device ID if any.
8055 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00008056 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008057 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008058 CGF.Int64Ty, /*isSigned=*/true);
8059 } else {
8060 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8061 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008062
Samuel Antaodf158d52016-04-27 22:58:19 +00008063 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008064 llvm::Value *PointerNum =
8065 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00008066
Samuel Antaob68e2db2016-03-03 16:20:23 +00008067 // Return value of the runtime offloading call.
8068 llvm::Value *Return;
8069
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008070 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
8071 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008072
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008073 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008074 // The target region is an outlined function launched by the runtime
8075 // via calls __tgt_target() or __tgt_target_teams().
8076 //
8077 // __tgt_target() launches a target region with one team and one thread,
8078 // executing a serial region. This master thread may in turn launch
8079 // more threads within its team upon encountering a parallel region,
8080 // however, no additional teams can be launched on the device.
8081 //
8082 // __tgt_target_teams() launches a target region with one or more teams,
8083 // each with one or more threads. This call is required for target
8084 // constructs such as:
8085 // 'target teams'
8086 // 'target' / 'teams'
8087 // 'target teams distribute parallel for'
8088 // 'target parallel'
8089 // and so on.
8090 //
8091 // Note that on the host and CPU targets, the runtime implementation of
8092 // these calls simply call the outlined function without forking threads.
8093 // The outlined functions themselves have runtime calls to
8094 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
8095 // the compiler in emitTeamsCall() and emitParallelCall().
8096 //
8097 // In contrast, on the NVPTX target, the implementation of
8098 // __tgt_target_teams() launches a GPU kernel with the requested number
8099 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00008100 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008101 // If we have NumTeams defined this means that we have an enclosed teams
8102 // region. Therefore we also expect to have NumThreads defined. These two
8103 // values should be defined in the presence of a teams directive,
8104 // regardless of having any clauses associated. If the user is using teams
8105 // but no clauses, these two values will be the default that should be
8106 // passed to the runtime library - a 32-bit integer with the value zero.
8107 assert(NumThreads && "Thread limit expression should be available along "
8108 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00008109 llvm::Value *OffloadingArgs[] = {DeviceID,
8110 OutlinedFnID,
8111 PointerNum,
8112 InputInfo.BasePointersArray.getPointer(),
8113 InputInfo.PointersArray.getPointer(),
8114 InputInfo.SizesArray.getPointer(),
8115 MapTypesArray,
8116 NumTeams,
8117 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00008118 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008119 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8120 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008121 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008122 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008123 llvm::Value *OffloadingArgs[] = {DeviceID,
8124 OutlinedFnID,
8125 PointerNum,
8126 InputInfo.BasePointersArray.getPointer(),
8127 InputInfo.PointersArray.getPointer(),
8128 InputInfo.SizesArray.getPointer(),
8129 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008130 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008131 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8132 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008133 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008134 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008135
Alexey Bataev2a007e02017-10-02 14:20:58 +00008136 // Check the error code and execute the host version if required.
8137 llvm::BasicBlock *OffloadFailedBlock =
8138 CGF.createBasicBlock("omp_offload.failed");
8139 llvm::BasicBlock *OffloadContBlock =
8140 CGF.createBasicBlock("omp_offload.cont");
8141 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8142 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8143
8144 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008145 if (RequiresOuterTask) {
8146 CapturedVars.clear();
8147 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8148 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008149 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008150 CGF.EmitBranch(OffloadContBlock);
8151
8152 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008153 };
8154
Samuel Antaoee8fb302016-01-06 13:42:12 +00008155 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008156 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8157 RequiresOuterTask](CodeGenFunction &CGF,
8158 PrePostActionTy &) {
8159 if (RequiresOuterTask) {
8160 CapturedVars.clear();
8161 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8162 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008163 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008164 };
8165
8166 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8167 &CapturedVars, RequiresOuterTask,
8168 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8169 // Fill up the arrays with all the captured variables.
8170 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8171 MappableExprsHandler::MapValuesArrayTy Pointers;
8172 MappableExprsHandler::MapValuesArrayTy Sizes;
8173 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8174
Alexey Bataev8451efa2018-01-15 19:06:12 +00008175 // Get mappable expression information.
8176 MappableExprsHandler MEHandler(D, CGF);
8177
8178 auto RI = CS.getCapturedRecordDecl()->field_begin();
8179 auto CV = CapturedVars.begin();
8180 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8181 CE = CS.capture_end();
8182 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008183 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8184 MappableExprsHandler::MapValuesArrayTy CurPointers;
8185 MappableExprsHandler::MapValuesArrayTy CurSizes;
8186 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8187 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008188
8189 // VLA sizes are passed to the outlined region by copy and do not have map
8190 // information associated.
8191 if (CI->capturesVariableArrayType()) {
8192 CurBasePointers.push_back(*CV);
8193 CurPointers.push_back(*CV);
8194 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8195 // Copy to the device as an argument. No need to retrieve it.
8196 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8197 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8198 } else {
8199 // If we have any information in the map clause, we use it, otherwise we
8200 // just do a default mapping.
8201 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008202 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008203 if (CurBasePointers.empty())
8204 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8205 CurPointers, CurSizes, CurMapTypes);
Alexey Bataev60705422018-10-30 15:50:12 +00008206 // Generate correct mapping for variables captured by reference in
8207 // lambdas.
8208 if (CI->capturesVariable())
8209 MEHandler.generateInfoForLambdaCaptures(CI->getCapturedVar(), *CV,
8210 CurBasePointers, CurPointers,
8211 CurSizes, CurMapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008212 }
8213 // We expect to have at least an element of information for this capture.
8214 assert(!CurBasePointers.empty() &&
8215 "Non-existing map pointer for capture!");
8216 assert(CurBasePointers.size() == CurPointers.size() &&
8217 CurBasePointers.size() == CurSizes.size() &&
8218 CurBasePointers.size() == CurMapTypes.size() &&
8219 "Inconsistent map information sizes!");
8220
Alexey Bataevb3638132018-07-19 16:34:13 +00008221 // If there is an entry in PartialStruct it means we have a struct with
8222 // individual members mapped. Emit an extra combined entry.
8223 if (PartialStruct.Base.isValid())
8224 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8225 CurMapTypes, PartialStruct);
8226
Alexey Bataev8451efa2018-01-15 19:06:12 +00008227 // We need to append the results of this capture to what we already have.
8228 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8229 Pointers.append(CurPointers.begin(), CurPointers.end());
8230 Sizes.append(CurSizes.begin(), CurSizes.end());
8231 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8232 }
Alexey Bataev60705422018-10-30 15:50:12 +00008233 // Adjust MEMBER_OF flags for the lambdas captures.
8234 MEHandler.adjustMemberOfForLambdaCaptures(BasePointers, Pointers, MapTypes);
Alexey Bataev92327c52018-03-26 16:40:55 +00008235 // Map other list items in the map clause which are not captured variables
8236 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008237 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8238 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008239
8240 TargetDataInfo Info;
8241 // Fill up the arrays and create the arguments.
8242 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8243 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8244 Info.PointersArray, Info.SizesArray,
8245 Info.MapTypesArray, Info);
8246 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8247 InputInfo.BasePointersArray =
8248 Address(Info.BasePointersArray, CGM.getPointerAlign());
8249 InputInfo.PointersArray =
8250 Address(Info.PointersArray, CGM.getPointerAlign());
8251 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8252 MapTypesArray = Info.MapTypesArray;
8253 if (RequiresOuterTask)
8254 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8255 else
8256 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8257 };
8258
8259 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8260 CodeGenFunction &CGF, PrePostActionTy &) {
8261 if (RequiresOuterTask) {
8262 CodeGenFunction::OMPTargetDataInfo InputInfo;
8263 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8264 } else {
8265 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8266 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008267 };
8268
8269 // If we have a target function ID it means that we need to support
8270 // offloading, otherwise, just execute on the host. We need to execute on host
8271 // regardless of the conditional in the if clause if, e.g., the user do not
8272 // specify target triples.
8273 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008274 if (IfCond) {
8275 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8276 } else {
8277 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008278 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008279 }
8280 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008281 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008282 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008283 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008284}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008285
8286void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8287 StringRef ParentName) {
8288 if (!S)
8289 return;
8290
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008291 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008292 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008293 isa<OMPExecutableDirective>(S) &&
8294 isOpenMPTargetExecutionDirective(
8295 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008296
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008297 if (RequiresDeviceCodegen) {
8298 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008299 unsigned DeviceID;
8300 unsigned FileID;
8301 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008302 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008303 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008304
8305 // Is this a target region that should not be emitted as an entry point? If
8306 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008307 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8308 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008309 return;
8310
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008311 switch (E.getDirectiveKind()) {
8312 case OMPD_target:
8313 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8314 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008315 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008316 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008317 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008318 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008319 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008320 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008321 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008322 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008323 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008324 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008325 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008326 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008327 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008328 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008329 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008330 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008331 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008332 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008333 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008334 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008335 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008336 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008337 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008338 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008339 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008340 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008341 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008342 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008343 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008344 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008345 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8346 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008347 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008348 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008349 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008350 CodeGenFunction::
8351 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8352 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008353 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008354 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008355 case OMPD_parallel:
8356 case OMPD_for:
8357 case OMPD_parallel_for:
8358 case OMPD_parallel_sections:
8359 case OMPD_for_simd:
8360 case OMPD_parallel_for_simd:
8361 case OMPD_cancel:
8362 case OMPD_cancellation_point:
8363 case OMPD_ordered:
8364 case OMPD_threadprivate:
8365 case OMPD_task:
8366 case OMPD_simd:
8367 case OMPD_sections:
8368 case OMPD_section:
8369 case OMPD_single:
8370 case OMPD_master:
8371 case OMPD_critical:
8372 case OMPD_taskyield:
8373 case OMPD_barrier:
8374 case OMPD_taskwait:
8375 case OMPD_taskgroup:
8376 case OMPD_atomic:
8377 case OMPD_flush:
8378 case OMPD_teams:
8379 case OMPD_target_data:
8380 case OMPD_target_exit_data:
8381 case OMPD_target_enter_data:
8382 case OMPD_distribute:
8383 case OMPD_distribute_simd:
8384 case OMPD_distribute_parallel_for:
8385 case OMPD_distribute_parallel_for_simd:
8386 case OMPD_teams_distribute:
8387 case OMPD_teams_distribute_simd:
8388 case OMPD_teams_distribute_parallel_for:
8389 case OMPD_teams_distribute_parallel_for_simd:
8390 case OMPD_target_update:
8391 case OMPD_declare_simd:
8392 case OMPD_declare_target:
8393 case OMPD_end_declare_target:
8394 case OMPD_declare_reduction:
8395 case OMPD_taskloop:
8396 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008397 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008398 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008399 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8400 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008401 return;
8402 }
8403
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008404 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008405 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008406 return;
8407
8408 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008409 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008410 return;
8411 }
8412
8413 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008414 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008415 S = L->getBody();
8416
8417 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008418 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008419 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008420}
8421
8422bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008423 // If emitting code for the host, we do not process FD here. Instead we do
8424 // the normal code generation.
8425 if (!CGM.getLangOpts().OpenMPIsDevice)
8426 return false;
8427
8428 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008429 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
8430 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
8431 scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
Samuel Antaoee8fb302016-01-06 13:42:12 +00008432
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008433 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008434 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
8435 AlreadyEmittedTargetFunctions.count(VD->getCanonicalDecl()) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008436}
8437
8438bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8439 if (!CGM.getLangOpts().OpenMPIsDevice)
8440 return false;
8441
8442 // Check if there are Ctors/Dtors in this declaration and look for target
8443 // regions in it. We use the complete variant to produce the kernel name
8444 // mangling.
8445 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008446 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8447 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008448 StringRef ParentName =
8449 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8450 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8451 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008452 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008453 StringRef ParentName =
8454 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8455 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8456 }
8457 }
8458
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008459 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008460 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008461 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8462 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008463 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008464 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008465 return true;
8466 }
8467 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008468}
8469
Alexey Bataev03f270c2018-03-30 18:31:07 +00008470void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8471 llvm::Constant *Addr) {
8472 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008473 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00008474 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8475 StringRef VarName;
8476 CharUnits VarSize;
8477 llvm::GlobalValue::LinkageTypes Linkage;
8478 switch (*Res) {
8479 case OMPDeclareTargetDeclAttr::MT_To:
8480 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8481 VarName = CGM.getMangledName(VD);
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00008482 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8483 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8484 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8485 } else {
8486 VarSize = CharUnits::Zero();
8487 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00008488 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
Alexey Bataev38235142018-07-31 16:40:15 +00008489 // Temp solution to prevent optimizations of the internal variables.
8490 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8491 std::string RefName = getName({VarName, "ref"});
8492 if (!CGM.GetGlobalValue(RefName)) {
8493 llvm::Constant *AddrRef =
8494 getOrCreateInternalVariable(Addr->getType(), RefName);
8495 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8496 GVAddrRef->setConstant(/*Val=*/true);
8497 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8498 GVAddrRef->setInitializer(Addr);
8499 CGM.addCompilerUsedGlobal(GVAddrRef);
8500 }
8501 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00008502 break;
8503 case OMPDeclareTargetDeclAttr::MT_Link:
Alexey Bataevc52f01d2018-07-16 20:05:25 +00008504 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8505 if (CGM.getLangOpts().OpenMPIsDevice) {
8506 VarName = Addr->getName();
8507 Addr = nullptr;
8508 } else {
8509 VarName = getAddrOfDeclareTargetLink(VD).getName();
Alexey Bataev03f270c2018-03-30 18:31:07 +00008510 Addr =
8511 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8512 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00008513 VarSize = CGM.getPointerSize();
8514 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8515 break;
8516 }
8517 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8518 VarName, Addr, VarSize, Flags, Linkage);
8519 }
8520}
8521
Samuel Antaoee8fb302016-01-06 13:42:12 +00008522bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008523 if (isa<FunctionDecl>(GD.getDecl()) ||
8524 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008525 return emitTargetFunctions(GD);
8526
8527 return emitTargetGlobalVariable(GD);
8528}
8529
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008530void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8531 for (const VarDecl *VD : DeferredGlobalVariables) {
8532 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008533 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008534 if (!Res)
8535 continue;
8536 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008537 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008538 } else {
8539 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8540 "Expected to or link clauses.");
8541 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008542 }
8543 }
8544}
8545
Alexey Bataev60705422018-10-30 15:50:12 +00008546void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
8547 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
8548 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
8549 " Expected target-based directive.");
8550}
8551
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008552CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8553 CodeGenModule &CGM)
8554 : CGM(CGM) {
8555 if (CGM.getLangOpts().OpenMPIsDevice) {
8556 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8557 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8558 }
8559}
8560
8561CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8562 if (CGM.getLangOpts().OpenMPIsDevice)
8563 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8564}
8565
Alexey Bataev6d944102018-05-02 15:45:28 +00008566bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008567 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8568 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008569
Alexey Bataev6d944102018-05-02 15:45:28 +00008570 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008571 const FunctionDecl *FD = D->getCanonicalDecl();
Alexey Bataev34f8a702018-03-28 14:28:54 +00008572 // Do not to emit function if it is marked as declare target as it was already
8573 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008574 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev34f8a702018-03-28 14:28:54 +00008575 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
8576 if (auto *F = dyn_cast_or_null<llvm::Function>(
Alexey Bataev6d944102018-05-02 15:45:28 +00008577 CGM.GetGlobalValue(CGM.getMangledName(GD))))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008578 return !F->isDeclaration();
8579 return false;
8580 }
8581 return true;
8582 }
8583
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008584 return !AlreadyEmittedTargetFunctions.insert(FD).second;
8585}
8586
Samuel Antaoee8fb302016-01-06 13:42:12 +00008587llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8588 // If we have offloading in the current module, we need to emit the entries
8589 // now and register the offloading descriptor.
8590 createOffloadEntriesAndInfoMetadata();
8591
8592 // Create and register the offloading binary descriptors. This is the main
8593 // entity that captures all the information about offloading in the current
8594 // compilation unit.
8595 return createOffloadingBinaryDescriptorRegistration();
8596}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008597
8598void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8599 const OMPExecutableDirective &D,
8600 SourceLocation Loc,
8601 llvm::Value *OutlinedFn,
8602 ArrayRef<llvm::Value *> CapturedVars) {
8603 if (!CGF.HaveInsertPoint())
8604 return;
8605
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008606 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008607 CodeGenFunction::RunCleanupsScope Scope(CGF);
8608
8609 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8610 llvm::Value *Args[] = {
8611 RTLoc,
8612 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8613 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8614 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8615 RealArgs.append(std::begin(Args), std::end(Args));
8616 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8617
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008618 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008619 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8620}
8621
8622void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008623 const Expr *NumTeams,
8624 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008625 SourceLocation Loc) {
8626 if (!CGF.HaveInsertPoint())
8627 return;
8628
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008629 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008630
Carlo Bertollic6872252016-04-04 15:55:02 +00008631 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008632 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008633 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8634 CGF.CGM.Int32Ty, /* isSigned = */ true)
8635 : CGF.Builder.getInt32(0);
8636
8637 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008638 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008639 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8640 CGF.CGM.Int32Ty, /* isSigned = */ true)
8641 : CGF.Builder.getInt32(0);
8642
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008643 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008644 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8645 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008646 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8647 PushNumTeamsArgs);
8648}
Samuel Antaodf158d52016-04-27 22:58:19 +00008649
Samuel Antaocc10b852016-07-28 14:23:26 +00008650void CGOpenMPRuntime::emitTargetDataCalls(
8651 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8652 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008653 if (!CGF.HaveInsertPoint())
8654 return;
8655
Samuel Antaocc10b852016-07-28 14:23:26 +00008656 // Action used to replace the default codegen action and turn privatization
8657 // off.
8658 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008659
8660 // Generate the code for the opening of the data environment. Capture all the
8661 // arguments of the runtime call by reference because they are used in the
8662 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008663 auto &&BeginThenGen = [this, &D, Device, &Info,
8664 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008665 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008666 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008667 MappableExprsHandler::MapValuesArrayTy Pointers;
8668 MappableExprsHandler::MapValuesArrayTy Sizes;
8669 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8670
8671 // Get map clause information.
8672 MappableExprsHandler MCHandler(D, CGF);
8673 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008674
8675 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008676 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008677
8678 llvm::Value *BasePointersArrayArg = nullptr;
8679 llvm::Value *PointersArrayArg = nullptr;
8680 llvm::Value *SizesArrayArg = nullptr;
8681 llvm::Value *MapTypesArrayArg = nullptr;
8682 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008683 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008684
8685 // Emit device ID if any.
8686 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008687 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008688 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008689 CGF.Int64Ty, /*isSigned=*/true);
8690 } else {
8691 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8692 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008693
8694 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008695 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008696
8697 llvm::Value *OffloadingArgs[] = {
8698 DeviceID, PointerNum, BasePointersArrayArg,
8699 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008700 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008701 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008702
8703 // If device pointer privatization is required, emit the body of the region
8704 // here. It will have to be duplicated: with and without privatization.
8705 if (!Info.CaptureDeviceAddrMap.empty())
8706 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008707 };
8708
8709 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008710 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8711 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008712 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008713
8714 llvm::Value *BasePointersArrayArg = nullptr;
8715 llvm::Value *PointersArrayArg = nullptr;
8716 llvm::Value *SizesArrayArg = nullptr;
8717 llvm::Value *MapTypesArrayArg = nullptr;
8718 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008719 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008720
8721 // Emit device ID if any.
8722 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008723 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008724 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008725 CGF.Int64Ty, /*isSigned=*/true);
8726 } else {
8727 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8728 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008729
8730 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008731 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008732
8733 llvm::Value *OffloadingArgs[] = {
8734 DeviceID, PointerNum, BasePointersArrayArg,
8735 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008736 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008737 OffloadingArgs);
8738 };
8739
Samuel Antaocc10b852016-07-28 14:23:26 +00008740 // If we need device pointer privatization, we need to emit the body of the
8741 // region with no privatization in the 'else' branch of the conditional.
8742 // Otherwise, we don't have to do anything.
8743 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8744 PrePostActionTy &) {
8745 if (!Info.CaptureDeviceAddrMap.empty()) {
8746 CodeGen.setAction(NoPrivAction);
8747 CodeGen(CGF);
8748 }
8749 };
8750
8751 // We don't have to do anything to close the region if the if clause evaluates
8752 // to false.
8753 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008754
8755 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008756 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008757 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008758 RegionCodeGenTy RCG(BeginThenGen);
8759 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008760 }
8761
Samuel Antaocc10b852016-07-28 14:23:26 +00008762 // If we don't require privatization of device pointers, we emit the body in
8763 // between the runtime calls. This avoids duplicating the body code.
8764 if (Info.CaptureDeviceAddrMap.empty()) {
8765 CodeGen.setAction(NoPrivAction);
8766 CodeGen(CGF);
8767 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008768
8769 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008770 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008771 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008772 RegionCodeGenTy RCG(EndThenGen);
8773 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008774 }
8775}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008776
Samuel Antao8d2d7302016-05-26 18:30:22 +00008777void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008778 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8779 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008780 if (!CGF.HaveInsertPoint())
8781 return;
8782
Samuel Antao8dd66282016-04-27 23:14:30 +00008783 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008784 isa<OMPTargetExitDataDirective>(D) ||
8785 isa<OMPTargetUpdateDirective>(D)) &&
8786 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008787
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008788 CodeGenFunction::OMPTargetDataInfo InputInfo;
8789 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008790 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008791 auto &&ThenGen = [this, &D, Device, &InputInfo,
8792 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008793 // Emit device ID if any.
8794 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008795 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008796 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008797 CGF.Int64Ty, /*isSigned=*/true);
8798 } else {
8799 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8800 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008801
8802 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008803 llvm::Constant *PointerNum =
8804 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008805
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008806 llvm::Value *OffloadingArgs[] = {DeviceID,
8807 PointerNum,
8808 InputInfo.BasePointersArray.getPointer(),
8809 InputInfo.PointersArray.getPointer(),
8810 InputInfo.SizesArray.getPointer(),
8811 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008812
Samuel Antao8d2d7302016-05-26 18:30:22 +00008813 // Select the right runtime function call for each expected standalone
8814 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008815 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008816 OpenMPRTLFunction RTLFn;
8817 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008818 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008819 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8820 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008821 break;
8822 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008823 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8824 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008825 break;
8826 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008827 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8828 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008829 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008830 case OMPD_parallel:
8831 case OMPD_for:
8832 case OMPD_parallel_for:
8833 case OMPD_parallel_sections:
8834 case OMPD_for_simd:
8835 case OMPD_parallel_for_simd:
8836 case OMPD_cancel:
8837 case OMPD_cancellation_point:
8838 case OMPD_ordered:
8839 case OMPD_threadprivate:
8840 case OMPD_task:
8841 case OMPD_simd:
8842 case OMPD_sections:
8843 case OMPD_section:
8844 case OMPD_single:
8845 case OMPD_master:
8846 case OMPD_critical:
8847 case OMPD_taskyield:
8848 case OMPD_barrier:
8849 case OMPD_taskwait:
8850 case OMPD_taskgroup:
8851 case OMPD_atomic:
8852 case OMPD_flush:
8853 case OMPD_teams:
8854 case OMPD_target_data:
8855 case OMPD_distribute:
8856 case OMPD_distribute_simd:
8857 case OMPD_distribute_parallel_for:
8858 case OMPD_distribute_parallel_for_simd:
8859 case OMPD_teams_distribute:
8860 case OMPD_teams_distribute_simd:
8861 case OMPD_teams_distribute_parallel_for:
8862 case OMPD_teams_distribute_parallel_for_simd:
8863 case OMPD_declare_simd:
8864 case OMPD_declare_target:
8865 case OMPD_end_declare_target:
8866 case OMPD_declare_reduction:
8867 case OMPD_taskloop:
8868 case OMPD_taskloop_simd:
8869 case OMPD_target:
8870 case OMPD_target_simd:
8871 case OMPD_target_teams_distribute:
8872 case OMPD_target_teams_distribute_simd:
8873 case OMPD_target_teams_distribute_parallel_for:
8874 case OMPD_target_teams_distribute_parallel_for_simd:
8875 case OMPD_target_teams:
8876 case OMPD_target_parallel:
8877 case OMPD_target_parallel_for:
8878 case OMPD_target_parallel_for_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008879 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008880 case OMPD_unknown:
8881 llvm_unreachable("Unexpected standalone target data directive.");
8882 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008883 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008884 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008885 };
8886
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008887 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8888 CodeGenFunction &CGF, PrePostActionTy &) {
8889 // Fill up the arrays with all the mapped variables.
8890 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8891 MappableExprsHandler::MapValuesArrayTy Pointers;
8892 MappableExprsHandler::MapValuesArrayTy Sizes;
8893 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008894
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008895 // Get map clause information.
8896 MappableExprsHandler MEHandler(D, CGF);
8897 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8898
8899 TargetDataInfo Info;
8900 // Fill up the arrays and create the arguments.
8901 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8902 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8903 Info.PointersArray, Info.SizesArray,
8904 Info.MapTypesArray, Info);
8905 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8906 InputInfo.BasePointersArray =
8907 Address(Info.BasePointersArray, CGM.getPointerAlign());
8908 InputInfo.PointersArray =
8909 Address(Info.PointersArray, CGM.getPointerAlign());
8910 InputInfo.SizesArray =
8911 Address(Info.SizesArray, CGM.getPointerAlign());
8912 MapTypesArray = Info.MapTypesArray;
8913 if (D.hasClausesOfKind<OMPDependClause>())
8914 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8915 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008916 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008917 };
8918
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008919 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008920 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8921 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008922 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008923 RegionCodeGenTy ThenRCG(TargetThenGen);
8924 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008925 }
8926}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008927
8928namespace {
8929 /// Kind of parameter in a function with 'declare simd' directive.
8930 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8931 /// Attribute set of the parameter.
8932 struct ParamAttrTy {
8933 ParamKindTy Kind = Vector;
8934 llvm::APSInt StrideOrArg;
8935 llvm::APSInt Alignment;
8936 };
8937} // namespace
8938
8939static unsigned evaluateCDTSize(const FunctionDecl *FD,
8940 ArrayRef<ParamAttrTy> ParamAttrs) {
8941 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8942 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8943 // of that clause. The VLEN value must be power of 2.
8944 // In other case the notion of the function`s "characteristic data type" (CDT)
8945 // is used to compute the vector length.
8946 // CDT is defined in the following order:
8947 // a) For non-void function, the CDT is the return type.
8948 // b) If the function has any non-uniform, non-linear parameters, then the
8949 // CDT is the type of the first such parameter.
8950 // c) If the CDT determined by a) or b) above is struct, union, or class
8951 // type which is pass-by-value (except for the type that maps to the
8952 // built-in complex data type), the characteristic data type is int.
8953 // d) If none of the above three cases is applicable, the CDT is int.
8954 // The VLEN is then determined based on the CDT and the size of vector
8955 // register of that ISA for which current vector version is generated. The
8956 // VLEN is computed using the formula below:
8957 // VLEN = sizeof(vector_register) / sizeof(CDT),
8958 // where vector register size specified in section 3.2.1 Registers and the
8959 // Stack Frame of original AMD64 ABI document.
8960 QualType RetType = FD->getReturnType();
8961 if (RetType.isNull())
8962 return 0;
8963 ASTContext &C = FD->getASTContext();
8964 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008965 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008966 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008967 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008968 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008969 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008970 if (ParamAttrs[Offset].Kind == Vector)
8971 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8972 ++Offset;
8973 }
8974 if (CDT.isNull()) {
8975 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8976 if (ParamAttrs[I + Offset].Kind == Vector) {
8977 CDT = FD->getParamDecl(I)->getType();
8978 break;
8979 }
8980 }
8981 }
8982 }
8983 if (CDT.isNull())
8984 CDT = C.IntTy;
8985 CDT = CDT->getCanonicalTypeUnqualified();
8986 if (CDT->isRecordType() || CDT->isUnionType())
8987 CDT = C.IntTy;
8988 return C.getTypeSize(CDT);
8989}
8990
8991static void
8992emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00008993 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008994 ArrayRef<ParamAttrTy> ParamAttrs,
8995 OMPDeclareSimdDeclAttr::BranchStateTy State) {
8996 struct ISADataTy {
8997 char ISA;
8998 unsigned VecRegSize;
8999 };
9000 ISADataTy ISAData[] = {
9001 {
9002 'b', 128
9003 }, // SSE
9004 {
9005 'c', 256
9006 }, // AVX
9007 {
9008 'd', 256
9009 }, // AVX2
9010 {
9011 'e', 512
9012 }, // AVX512
9013 };
9014 llvm::SmallVector<char, 2> Masked;
9015 switch (State) {
9016 case OMPDeclareSimdDeclAttr::BS_Undefined:
9017 Masked.push_back('N');
9018 Masked.push_back('M');
9019 break;
9020 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
9021 Masked.push_back('N');
9022 break;
9023 case OMPDeclareSimdDeclAttr::BS_Inbranch:
9024 Masked.push_back('M');
9025 break;
9026 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009027 for (char Mask : Masked) {
9028 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009029 SmallString<256> Buffer;
9030 llvm::raw_svector_ostream Out(Buffer);
9031 Out << "_ZGV" << Data.ISA << Mask;
9032 if (!VLENVal) {
9033 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
9034 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009035 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009036 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009037 }
9038 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009039 switch (ParamAttr.Kind){
9040 case LinearWithVarStride:
9041 Out << 's' << ParamAttr.StrideOrArg;
9042 break;
9043 case Linear:
9044 Out << 'l';
9045 if (!!ParamAttr.StrideOrArg)
9046 Out << ParamAttr.StrideOrArg;
9047 break;
9048 case Uniform:
9049 Out << 'u';
9050 break;
9051 case Vector:
9052 Out << 'v';
9053 break;
9054 }
9055 if (!!ParamAttr.Alignment)
9056 Out << 'a' << ParamAttr.Alignment;
9057 }
9058 Out << '_' << Fn->getName();
9059 Fn->addFnAttr(Out.str());
9060 }
9061 }
9062}
9063
9064void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
9065 llvm::Function *Fn) {
9066 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009067 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009068 // Map params to their positions in function decl.
9069 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
9070 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009071 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009072 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009073 for (const ParmVarDecl *P : FD->parameters()) {
9074 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009075 ++ParamPos;
9076 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009077 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009078 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009079 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
9080 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009081 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009082 E = E->IgnoreParenImpCasts();
9083 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009084 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009085 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009086 } else {
9087 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9088 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009089 Pos = ParamPositions[PVD];
9090 }
9091 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009092 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009093 // Get alignment info.
9094 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009095 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009096 E = E->IgnoreParenImpCasts();
9097 unsigned Pos;
9098 QualType ParmTy;
9099 if (isa<CXXThisExpr>(E)) {
9100 Pos = ParamPositions[FD];
9101 ParmTy = E->getType();
9102 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009103 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9104 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009105 Pos = ParamPositions[PVD];
9106 ParmTy = PVD->getType();
9107 }
9108 ParamAttrs[Pos].Alignment =
9109 (*NI)
9110 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009111 : llvm::APSInt::getUnsigned(
9112 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
9113 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009114 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009115 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009116 // Mark linear parameters.
9117 auto SI = Attr->steps_begin();
9118 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009119 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009120 E = E->IgnoreParenImpCasts();
9121 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009122 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009123 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009124 } else {
9125 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9126 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009127 Pos = ParamPositions[PVD];
9128 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009129 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009130 ParamAttr.Kind = Linear;
9131 if (*SI) {
9132 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
9133 Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009134 if (const auto *DRE =
9135 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9136 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009137 ParamAttr.Kind = LinearWithVarStride;
9138 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9139 ParamPositions[StridePVD->getCanonicalDecl()]);
9140 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009141 }
9142 }
9143 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009144 ++SI;
9145 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009146 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009147 llvm::APSInt VLENVal;
9148 if (const Expr *VLEN = Attr->getSimdlen())
9149 VLENVal = VLEN->EvaluateKnownConstInt(C);
9150 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9151 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9152 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9153 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009154 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009155 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009156 }
9157}
Alexey Bataev8b427062016-05-25 12:36:08 +00009158
9159namespace {
9160/// Cleanup action for doacross support.
9161class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9162public:
9163 static const int DoacrossFinArgs = 2;
9164
9165private:
9166 llvm::Value *RTLFn;
9167 llvm::Value *Args[DoacrossFinArgs];
9168
9169public:
9170 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
9171 : RTLFn(RTLFn) {
9172 assert(CallArgs.size() == DoacrossFinArgs);
9173 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9174 }
9175 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9176 if (!CGF.HaveInsertPoint())
9177 return;
9178 CGF.EmitRuntimeCall(RTLFn, Args);
9179 }
9180};
9181} // namespace
9182
9183void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009184 const OMPLoopDirective &D,
9185 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009186 if (!CGF.HaveInsertPoint())
9187 return;
9188
9189 ASTContext &C = CGM.getContext();
9190 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9191 RecordDecl *RD;
9192 if (KmpDimTy.isNull()) {
9193 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9194 // kmp_int64 lo; // lower
9195 // kmp_int64 up; // upper
9196 // kmp_int64 st; // stride
9197 // };
9198 RD = C.buildImplicitRecord("kmp_dim");
9199 RD->startDefinition();
9200 addFieldToRecordDecl(C, RD, Int64Ty);
9201 addFieldToRecordDecl(C, RD, Int64Ty);
9202 addFieldToRecordDecl(C, RD, Int64Ty);
9203 RD->completeDefinition();
9204 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009205 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009206 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009207 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009208 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9209 QualType ArrayTy =
9210 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009211
Alexey Bataevf138fda2018-08-13 19:04:24 +00009212 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9213 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009214 enum { LowerFD = 0, UpperFD, StrideFD };
9215 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009216 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
9217 LValue DimsLVal =
9218 CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP(
9219 DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)),
9220 KmpDimTy);
9221 // dims.upper = num_iterations;
9222 LValue UpperLVal = CGF.EmitLValueForField(
9223 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9224 llvm::Value *NumIterVal =
9225 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9226 D.getNumIterations()->getType(), Int64Ty,
9227 D.getNumIterations()->getExprLoc());
9228 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9229 // dims.stride = 1;
9230 LValue StrideLVal = CGF.EmitLValueForField(
9231 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9232 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9233 StrideLVal);
9234 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009235
9236 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9237 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009238 llvm::Value *Args[] = {
9239 emitUpdateLocation(CGF, D.getBeginLoc()),
9240 getThreadID(CGF, D.getBeginLoc()),
9241 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9242 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
9243 CGF.Builder
9244 .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy))
9245 .getPointer(),
9246 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009247
9248 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
9249 CGF.EmitRuntimeCall(RTLFn, Args);
9250 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009251 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
Alexey Bataev8b427062016-05-25 12:36:08 +00009252 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
9253 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9254 llvm::makeArrayRef(FiniArgs));
9255}
9256
9257void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9258 const OMPDependClause *C) {
9259 QualType Int64Ty =
9260 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009261 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9262 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9263 Int64Ty, Size, ArrayType::Normal, 0);
9264 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9265 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9266 const Expr *CounterVal = C->getLoopData(I);
9267 assert(CounterVal);
9268 llvm::Value *CntVal = CGF.EmitScalarConversion(
9269 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9270 CounterVal->getExprLoc());
9271 CGF.EmitStoreOfScalar(
9272 CntVal,
9273 CGF.Builder.CreateConstArrayGEP(
9274 CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)),
9275 /*Volatile=*/false, Int64Ty);
9276 }
9277 llvm::Value *Args[] = {
9278 emitUpdateLocation(CGF, C->getBeginLoc()),
9279 getThreadID(CGF, C->getBeginLoc()),
9280 CGF.Builder
9281 .CreateConstArrayGEP(CntAddr, 0,
9282 CGM.getContext().getTypeSizeInChars(Int64Ty))
9283 .getPointer()};
Alexey Bataev8b427062016-05-25 12:36:08 +00009284 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009285 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009286 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009287 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009288 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9289 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9290 }
9291 CGF.EmitRuntimeCall(RTLFn, Args);
9292}
9293
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009294void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
9295 llvm::Value *Callee,
9296 ArrayRef<llvm::Value *> Args) const {
9297 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009298 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9299
9300 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009301 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009302 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009303 return;
9304 }
9305 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009306 CGF.EmitRuntimeCall(Callee, Args);
9307}
9308
9309void CGOpenMPRuntime::emitOutlinedFunctionCall(
9310 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
9311 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009312 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009313}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009314
9315Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9316 const VarDecl *NativeParam,
9317 const VarDecl *TargetParam) const {
9318 return CGF.GetAddrOfLocalVar(NativeParam);
9319}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009320
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009321Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9322 const VarDecl *VD) {
9323 return Address::invalid();
9324}
9325
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009326llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
9327 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9328 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9329 llvm_unreachable("Not supported in SIMD-only mode");
9330}
9331
9332llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
9333 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9334 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9335 llvm_unreachable("Not supported in SIMD-only mode");
9336}
9337
9338llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
9339 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9340 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9341 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9342 bool Tied, unsigned &NumberOfParts) {
9343 llvm_unreachable("Not supported in SIMD-only mode");
9344}
9345
9346void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9347 SourceLocation Loc,
9348 llvm::Value *OutlinedFn,
9349 ArrayRef<llvm::Value *> CapturedVars,
9350 const Expr *IfCond) {
9351 llvm_unreachable("Not supported in SIMD-only mode");
9352}
9353
9354void CGOpenMPSIMDRuntime::emitCriticalRegion(
9355 CodeGenFunction &CGF, StringRef CriticalName,
9356 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9357 const Expr *Hint) {
9358 llvm_unreachable("Not supported in SIMD-only mode");
9359}
9360
9361void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9362 const RegionCodeGenTy &MasterOpGen,
9363 SourceLocation Loc) {
9364 llvm_unreachable("Not supported in SIMD-only mode");
9365}
9366
9367void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9368 SourceLocation Loc) {
9369 llvm_unreachable("Not supported in SIMD-only mode");
9370}
9371
9372void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9373 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9374 SourceLocation Loc) {
9375 llvm_unreachable("Not supported in SIMD-only mode");
9376}
9377
9378void CGOpenMPSIMDRuntime::emitSingleRegion(
9379 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9380 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9381 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9382 ArrayRef<const Expr *> AssignmentOps) {
9383 llvm_unreachable("Not supported in SIMD-only mode");
9384}
9385
9386void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9387 const RegionCodeGenTy &OrderedOpGen,
9388 SourceLocation Loc,
9389 bool IsThreads) {
9390 llvm_unreachable("Not supported in SIMD-only mode");
9391}
9392
9393void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9394 SourceLocation Loc,
9395 OpenMPDirectiveKind Kind,
9396 bool EmitChecks,
9397 bool ForceSimpleCall) {
9398 llvm_unreachable("Not supported in SIMD-only mode");
9399}
9400
9401void CGOpenMPSIMDRuntime::emitForDispatchInit(
9402 CodeGenFunction &CGF, SourceLocation Loc,
9403 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9404 bool Ordered, const DispatchRTInput &DispatchValues) {
9405 llvm_unreachable("Not supported in SIMD-only mode");
9406}
9407
9408void CGOpenMPSIMDRuntime::emitForStaticInit(
9409 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9410 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9411 llvm_unreachable("Not supported in SIMD-only mode");
9412}
9413
9414void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9415 CodeGenFunction &CGF, SourceLocation Loc,
9416 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9417 llvm_unreachable("Not supported in SIMD-only mode");
9418}
9419
9420void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9421 SourceLocation Loc,
9422 unsigned IVSize,
9423 bool IVSigned) {
9424 llvm_unreachable("Not supported in SIMD-only mode");
9425}
9426
9427void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9428 SourceLocation Loc,
9429 OpenMPDirectiveKind DKind) {
9430 llvm_unreachable("Not supported in SIMD-only mode");
9431}
9432
9433llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9434 SourceLocation Loc,
9435 unsigned IVSize, bool IVSigned,
9436 Address IL, Address LB,
9437 Address UB, Address ST) {
9438 llvm_unreachable("Not supported in SIMD-only mode");
9439}
9440
9441void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9442 llvm::Value *NumThreads,
9443 SourceLocation Loc) {
9444 llvm_unreachable("Not supported in SIMD-only mode");
9445}
9446
9447void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9448 OpenMPProcBindClauseKind ProcBind,
9449 SourceLocation Loc) {
9450 llvm_unreachable("Not supported in SIMD-only mode");
9451}
9452
9453Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9454 const VarDecl *VD,
9455 Address VDAddr,
9456 SourceLocation Loc) {
9457 llvm_unreachable("Not supported in SIMD-only mode");
9458}
9459
9460llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9461 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9462 CodeGenFunction *CGF) {
9463 llvm_unreachable("Not supported in SIMD-only mode");
9464}
9465
9466Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9467 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9468 llvm_unreachable("Not supported in SIMD-only mode");
9469}
9470
9471void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9472 ArrayRef<const Expr *> Vars,
9473 SourceLocation Loc) {
9474 llvm_unreachable("Not supported in SIMD-only mode");
9475}
9476
9477void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9478 const OMPExecutableDirective &D,
9479 llvm::Value *TaskFunction,
9480 QualType SharedsTy, Address Shareds,
9481 const Expr *IfCond,
9482 const OMPTaskDataTy &Data) {
9483 llvm_unreachable("Not supported in SIMD-only mode");
9484}
9485
9486void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9487 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
9488 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
9489 const Expr *IfCond, const OMPTaskDataTy &Data) {
9490 llvm_unreachable("Not supported in SIMD-only mode");
9491}
9492
9493void CGOpenMPSIMDRuntime::emitReduction(
9494 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9495 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9496 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9497 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9498 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9499 ReductionOps, Options);
9500}
9501
9502llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9503 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9504 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9505 llvm_unreachable("Not supported in SIMD-only mode");
9506}
9507
9508void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9509 SourceLocation Loc,
9510 ReductionCodeGen &RCG,
9511 unsigned N) {
9512 llvm_unreachable("Not supported in SIMD-only mode");
9513}
9514
9515Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9516 SourceLocation Loc,
9517 llvm::Value *ReductionsPtr,
9518 LValue SharedLVal) {
9519 llvm_unreachable("Not supported in SIMD-only mode");
9520}
9521
9522void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9523 SourceLocation Loc) {
9524 llvm_unreachable("Not supported in SIMD-only mode");
9525}
9526
9527void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9528 CodeGenFunction &CGF, SourceLocation Loc,
9529 OpenMPDirectiveKind CancelRegion) {
9530 llvm_unreachable("Not supported in SIMD-only mode");
9531}
9532
9533void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9534 SourceLocation Loc, const Expr *IfCond,
9535 OpenMPDirectiveKind CancelRegion) {
9536 llvm_unreachable("Not supported in SIMD-only mode");
9537}
9538
9539void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9540 const OMPExecutableDirective &D, StringRef ParentName,
9541 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9542 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9543 llvm_unreachable("Not supported in SIMD-only mode");
9544}
9545
9546void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9547 const OMPExecutableDirective &D,
9548 llvm::Value *OutlinedFn,
9549 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00009550 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009551 llvm_unreachable("Not supported in SIMD-only mode");
9552}
9553
9554bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9555 llvm_unreachable("Not supported in SIMD-only mode");
9556}
9557
9558bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9559 llvm_unreachable("Not supported in SIMD-only mode");
9560}
9561
9562bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9563 return false;
9564}
9565
9566llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9567 return nullptr;
9568}
9569
9570void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9571 const OMPExecutableDirective &D,
9572 SourceLocation Loc,
9573 llvm::Value *OutlinedFn,
9574 ArrayRef<llvm::Value *> CapturedVars) {
9575 llvm_unreachable("Not supported in SIMD-only mode");
9576}
9577
9578void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9579 const Expr *NumTeams,
9580 const Expr *ThreadLimit,
9581 SourceLocation Loc) {
9582 llvm_unreachable("Not supported in SIMD-only mode");
9583}
9584
9585void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9586 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9587 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9588 llvm_unreachable("Not supported in SIMD-only mode");
9589}
9590
9591void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9592 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9593 const Expr *Device) {
9594 llvm_unreachable("Not supported in SIMD-only mode");
9595}
9596
9597void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009598 const OMPLoopDirective &D,
9599 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009600 llvm_unreachable("Not supported in SIMD-only mode");
9601}
9602
9603void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9604 const OMPDependClause *C) {
9605 llvm_unreachable("Not supported in SIMD-only mode");
9606}
9607
9608const VarDecl *
9609CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9610 const VarDecl *NativeParam) const {
9611 llvm_unreachable("Not supported in SIMD-only mode");
9612}
9613
9614Address
9615CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9616 const VarDecl *NativeParam,
9617 const VarDecl *TargetParam) const {
9618 llvm_unreachable("Not supported in SIMD-only mode");
9619}
9620