blob: 21881727b4a9b6deebe2a537fc428c30df05e21a [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 Bataev3eff5f42015-02-25 08:32:46 +00001488llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1489 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001490 unsigned Flags) {
1491 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001492 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001493 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001494 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001495 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001496
1497 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1498
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001499 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001500 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001501 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1502 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001503 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001504
Alexander Musmanc6388682014-12-15 07:07:06 +00001505 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1506 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001507 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001508 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001509 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001510 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001511 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001512 LocValue = AI;
1513
1514 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1515 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001516 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001517 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001518 }
1519
1520 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001521 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1522 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1523 LValue PSource =
1524 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001525
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001526 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001527 if (OMPDebugLoc == nullptr) {
1528 SmallString<128> Buffer2;
1529 llvm::raw_svector_ostream OS2(Buffer2);
1530 // Build debug location
1531 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1532 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001533 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001534 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001535 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1536 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1537 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001538 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001539 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001540 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001541
John McCall7f416cc2015-09-08 08:05:57 +00001542 // Our callers always pass this to a runtime function, so for
1543 // convenience, go ahead and return a naked pointer.
1544 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001545}
1546
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001547llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1548 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001549 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1550
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001551 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001552 // Check whether we've already cached a load of the thread id in this
1553 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001554 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001555 if (I != OpenMPLocThreadIDMap.end()) {
1556 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001557 if (ThreadID != nullptr)
1558 return ThreadID;
1559 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001560 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001561 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1562 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001563 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001564 if (auto *OMPRegionInfo =
1565 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1566 if (OMPRegionInfo->getThreadIDVariable()) {
1567 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001568 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001569 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001570 // If value loaded in entry block, cache it and use it everywhere in
1571 // function.
1572 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1573 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1574 Elem.second.ThreadID = ThreadID;
1575 }
1576 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001577 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001578 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001579 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001580
1581 // This is not an outlined function region - need to call __kmpc_int32
1582 // kmpc_global_thread_num(ident_t *loc).
1583 // Generate thread id value and cache this value for use across the
1584 // function.
1585 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1586 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001587 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001588 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1589 emitUpdateLocation(CGF, Loc));
1590 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001591 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001592 Elem.second.ThreadID = Call;
1593 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001594}
1595
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001596void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001597 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001598 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1599 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001600 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001601 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001602 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001603 FunctionUDRMap.erase(CGF.CurFn);
1604 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001605}
1606
1607llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001608 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001609}
1610
1611llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001612 if (!Kmpc_MicroTy) {
1613 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1614 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1615 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1616 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1617 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001618 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1619}
1620
1621llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001622CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001623 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001624 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001625 case OMPRTL__kmpc_fork_call: {
1626 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1627 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001628 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1629 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001630 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001631 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001632 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1633 break;
1634 }
1635 case OMPRTL__kmpc_global_thread_num: {
1636 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001637 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001638 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001639 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001640 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1641 break;
1642 }
Alexey Bataev97720002014-11-11 04:05:39 +00001643 case OMPRTL__kmpc_threadprivate_cached: {
1644 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1645 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1646 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1647 CGM.VoidPtrTy, CGM.SizeTy,
1648 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001649 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001650 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1651 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1652 break;
1653 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001654 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001655 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1656 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001657 llvm::Type *TypeParams[] = {
1658 getIdentTyPointerTy(), CGM.Int32Ty,
1659 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001660 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001661 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1662 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1663 break;
1664 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001665 case OMPRTL__kmpc_critical_with_hint: {
1666 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1667 // kmp_critical_name *crit, uintptr_t hint);
1668 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1669 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1670 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001671 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001672 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1673 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1674 break;
1675 }
Alexey Bataev97720002014-11-11 04:05:39 +00001676 case OMPRTL__kmpc_threadprivate_register: {
1677 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1678 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1679 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001680 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001681 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1682 /*isVarArg*/ false)->getPointerTo();
1683 // typedef void *(*kmpc_cctor)(void *, void *);
1684 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001685 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001686 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001687 /*isVarArg*/ false)
1688 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001689 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001690 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001691 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1692 ->getPointerTo();
1693 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1694 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001695 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001696 /*isVarArg*/ false);
1697 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1698 break;
1699 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001700 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001701 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1702 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001703 llvm::Type *TypeParams[] = {
1704 getIdentTyPointerTy(), CGM.Int32Ty,
1705 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001706 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001707 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1708 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1709 break;
1710 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001711 case OMPRTL__kmpc_cancel_barrier: {
1712 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1713 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001714 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001715 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001716 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1717 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001718 break;
1719 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001720 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001721 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001722 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001723 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001724 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1725 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1726 break;
1727 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001728 case OMPRTL__kmpc_for_static_fini: {
1729 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1730 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001731 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001732 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1733 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1734 break;
1735 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001736 case OMPRTL__kmpc_push_num_threads: {
1737 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1738 // kmp_int32 num_threads)
1739 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1740 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001741 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001742 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1743 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1744 break;
1745 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001746 case OMPRTL__kmpc_serialized_parallel: {
1747 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1748 // global_tid);
1749 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001750 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001751 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1752 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1753 break;
1754 }
1755 case OMPRTL__kmpc_end_serialized_parallel: {
1756 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1757 // global_tid);
1758 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001759 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001760 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1761 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1762 break;
1763 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001764 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001765 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001766 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001767 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001768 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001769 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1770 break;
1771 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001772 case OMPRTL__kmpc_master: {
1773 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001775 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001776 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1778 break;
1779 }
1780 case OMPRTL__kmpc_end_master: {
1781 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1782 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001783 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1785 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1786 break;
1787 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001788 case OMPRTL__kmpc_omp_taskyield: {
1789 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1790 // int end_part);
1791 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001792 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001793 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1794 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1795 break;
1796 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001797 case OMPRTL__kmpc_single: {
1798 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001800 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001801 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1802 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1803 break;
1804 }
1805 case OMPRTL__kmpc_end_single: {
1806 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1807 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001808 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001809 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1810 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1811 break;
1812 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001813 case OMPRTL__kmpc_omp_task_alloc: {
1814 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1815 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1816 // kmp_routine_entry_t *task_entry);
1817 assert(KmpRoutineEntryPtrTy != nullptr &&
1818 "Type kmp_routine_entry_t must be created.");
1819 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1820 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1821 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001822 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001823 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1824 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1825 break;
1826 }
1827 case OMPRTL__kmpc_omp_task: {
1828 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1829 // *new_task);
1830 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1831 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001832 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001833 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1834 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1835 break;
1836 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001837 case OMPRTL__kmpc_copyprivate: {
1838 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001839 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001840 // kmp_int32 didit);
1841 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1842 auto *CpyFnTy =
1843 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001844 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001845 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1846 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001847 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001848 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1849 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1850 break;
1851 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001852 case OMPRTL__kmpc_reduce: {
1853 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1854 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1855 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1856 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1857 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1858 /*isVarArg=*/false);
1859 llvm::Type *TypeParams[] = {
1860 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1861 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1862 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001863 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001864 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1865 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1866 break;
1867 }
1868 case OMPRTL__kmpc_reduce_nowait: {
1869 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1870 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1871 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1872 // *lck);
1873 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1874 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1875 /*isVarArg=*/false);
1876 llvm::Type *TypeParams[] = {
1877 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1878 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1879 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001880 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001881 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1882 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1883 break;
1884 }
1885 case OMPRTL__kmpc_end_reduce: {
1886 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1887 // kmp_critical_name *lck);
1888 llvm::Type *TypeParams[] = {
1889 getIdentTyPointerTy(), CGM.Int32Ty,
1890 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001891 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001892 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1893 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1894 break;
1895 }
1896 case OMPRTL__kmpc_end_reduce_nowait: {
1897 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1898 // kmp_critical_name *lck);
1899 llvm::Type *TypeParams[] = {
1900 getIdentTyPointerTy(), CGM.Int32Ty,
1901 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001902 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001903 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1904 RTLFn =
1905 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1906 break;
1907 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001908 case OMPRTL__kmpc_omp_task_begin_if0: {
1909 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1910 // *new_task);
1911 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1912 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001913 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001914 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1915 RTLFn =
1916 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1917 break;
1918 }
1919 case OMPRTL__kmpc_omp_task_complete_if0: {
1920 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1921 // *new_task);
1922 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1923 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001924 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001925 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1926 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1927 /*Name=*/"__kmpc_omp_task_complete_if0");
1928 break;
1929 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001930 case OMPRTL__kmpc_ordered: {
1931 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1932 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001933 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001934 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1935 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1936 break;
1937 }
1938 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001939 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001940 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001941 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001942 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1943 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1944 break;
1945 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001946 case OMPRTL__kmpc_omp_taskwait: {
1947 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1948 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001949 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001950 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1952 break;
1953 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001954 case OMPRTL__kmpc_taskgroup: {
1955 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1956 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001957 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001958 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1959 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1960 break;
1961 }
1962 case OMPRTL__kmpc_end_taskgroup: {
1963 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1964 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001965 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001966 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1967 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1968 break;
1969 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001970 case OMPRTL__kmpc_push_proc_bind: {
1971 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1972 // int proc_bind)
1973 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001974 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00001975 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1976 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1977 break;
1978 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001979 case OMPRTL__kmpc_omp_task_with_deps: {
1980 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1981 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1982 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1983 llvm::Type *TypeParams[] = {
1984 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1985 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001986 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001987 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1988 RTLFn =
1989 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1990 break;
1991 }
1992 case OMPRTL__kmpc_omp_wait_deps: {
1993 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1994 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1995 // kmp_depend_info_t *noalias_dep_list);
1996 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1997 CGM.Int32Ty, CGM.VoidPtrTy,
1998 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001999 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002000 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2001 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2002 break;
2003 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002004 case OMPRTL__kmpc_cancellationpoint: {
2005 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2006 // global_tid, kmp_int32 cncl_kind)
2007 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002008 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002009 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2010 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2011 break;
2012 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002013 case OMPRTL__kmpc_cancel: {
2014 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2015 // kmp_int32 cncl_kind)
2016 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002017 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002018 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2019 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2020 break;
2021 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002022 case OMPRTL__kmpc_push_num_teams: {
2023 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2024 // kmp_int32 num_teams, kmp_int32 num_threads)
2025 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2026 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002027 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002028 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2029 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2030 break;
2031 }
2032 case OMPRTL__kmpc_fork_teams: {
2033 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2034 // microtask, ...);
2035 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2036 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002037 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002038 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2039 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2040 break;
2041 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002042 case OMPRTL__kmpc_taskloop: {
2043 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2044 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2045 // sched, kmp_uint64 grainsize, void *task_dup);
2046 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2047 CGM.IntTy,
2048 CGM.VoidPtrTy,
2049 CGM.IntTy,
2050 CGM.Int64Ty->getPointerTo(),
2051 CGM.Int64Ty->getPointerTo(),
2052 CGM.Int64Ty,
2053 CGM.IntTy,
2054 CGM.IntTy,
2055 CGM.Int64Ty,
2056 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002057 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002058 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2059 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2060 break;
2061 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002062 case OMPRTL__kmpc_doacross_init: {
2063 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2064 // num_dims, struct kmp_dim *dims);
2065 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2066 CGM.Int32Ty,
2067 CGM.Int32Ty,
2068 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002069 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002070 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2071 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2072 break;
2073 }
2074 case OMPRTL__kmpc_doacross_fini: {
2075 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2076 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002077 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002078 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2079 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2080 break;
2081 }
2082 case OMPRTL__kmpc_doacross_post: {
2083 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2084 // *vec);
2085 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2086 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002087 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002088 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2089 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2090 break;
2091 }
2092 case OMPRTL__kmpc_doacross_wait: {
2093 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2094 // *vec);
2095 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2096 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002097 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002098 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2099 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2100 break;
2101 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002102 case OMPRTL__kmpc_task_reduction_init: {
2103 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2104 // *data);
2105 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002106 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002107 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2108 RTLFn =
2109 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2110 break;
2111 }
2112 case OMPRTL__kmpc_task_reduction_get_th_data: {
2113 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2114 // *d);
2115 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002116 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002117 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2118 RTLFn = CGM.CreateRuntimeFunction(
2119 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2120 break;
2121 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002122 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002123 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2124 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002125 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002126 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002127 CGM.VoidPtrTy,
2128 CGM.Int32Ty,
2129 CGM.VoidPtrPtrTy,
2130 CGM.VoidPtrPtrTy,
2131 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002132 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002133 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002134 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2135 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2136 break;
2137 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002138 case OMPRTL__tgt_target_nowait: {
2139 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2140 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2141 // int64_t *arg_types);
2142 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2143 CGM.VoidPtrTy,
2144 CGM.Int32Ty,
2145 CGM.VoidPtrPtrTy,
2146 CGM.VoidPtrPtrTy,
2147 CGM.SizeTy->getPointerTo(),
2148 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002149 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002150 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2151 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2152 break;
2153 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002154 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002155 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002156 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002157 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2158 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002159 CGM.VoidPtrTy,
2160 CGM.Int32Ty,
2161 CGM.VoidPtrPtrTy,
2162 CGM.VoidPtrPtrTy,
2163 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002164 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002165 CGM.Int32Ty,
2166 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002167 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002168 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2169 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2170 break;
2171 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002172 case OMPRTL__tgt_target_teams_nowait: {
2173 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2174 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2175 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2176 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2177 CGM.VoidPtrTy,
2178 CGM.Int32Ty,
2179 CGM.VoidPtrPtrTy,
2180 CGM.VoidPtrPtrTy,
2181 CGM.SizeTy->getPointerTo(),
2182 CGM.Int64Ty->getPointerTo(),
2183 CGM.Int32Ty,
2184 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002185 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002186 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2187 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2188 break;
2189 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002190 case OMPRTL__tgt_register_lib: {
2191 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2192 QualType ParamTy =
2193 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2194 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002195 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002196 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2197 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2198 break;
2199 }
2200 case OMPRTL__tgt_unregister_lib: {
2201 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2202 QualType ParamTy =
2203 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2204 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002205 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002206 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2207 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2208 break;
2209 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002210 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002211 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2212 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2213 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002214 CGM.Int32Ty,
2215 CGM.VoidPtrPtrTy,
2216 CGM.VoidPtrPtrTy,
2217 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002218 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002219 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002220 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2221 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2222 break;
2223 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002224 case OMPRTL__tgt_target_data_begin_nowait: {
2225 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2226 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2227 // *arg_types);
2228 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2229 CGM.Int32Ty,
2230 CGM.VoidPtrPtrTy,
2231 CGM.VoidPtrPtrTy,
2232 CGM.SizeTy->getPointerTo(),
2233 CGM.Int64Ty->getPointerTo()};
2234 auto *FnTy =
2235 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2236 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2237 break;
2238 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002239 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002240 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2241 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2242 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002243 CGM.Int32Ty,
2244 CGM.VoidPtrPtrTy,
2245 CGM.VoidPtrPtrTy,
2246 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002247 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002248 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002249 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2250 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2251 break;
2252 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002253 case OMPRTL__tgt_target_data_end_nowait: {
2254 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2255 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2256 // *arg_types);
2257 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2258 CGM.Int32Ty,
2259 CGM.VoidPtrPtrTy,
2260 CGM.VoidPtrPtrTy,
2261 CGM.SizeTy->getPointerTo(),
2262 CGM.Int64Ty->getPointerTo()};
2263 auto *FnTy =
2264 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2265 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2266 break;
2267 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002268 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002269 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2270 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2271 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002272 CGM.Int32Ty,
2273 CGM.VoidPtrPtrTy,
2274 CGM.VoidPtrPtrTy,
2275 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002276 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002277 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002278 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2279 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2280 break;
2281 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002282 case OMPRTL__tgt_target_data_update_nowait: {
2283 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2284 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2285 // *arg_types);
2286 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2287 CGM.Int32Ty,
2288 CGM.VoidPtrPtrTy,
2289 CGM.VoidPtrPtrTy,
2290 CGM.SizeTy->getPointerTo(),
2291 CGM.Int64Ty->getPointerTo()};
2292 auto *FnTy =
2293 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2294 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2295 break;
2296 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002297 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002298 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002299 return RTLFn;
2300}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002301
Alexander Musman21212e42015-03-13 10:38:23 +00002302llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2303 bool IVSigned) {
2304 assert((IVSize == 32 || IVSize == 64) &&
2305 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002306 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2307 : "__kmpc_for_static_init_4u")
2308 : (IVSigned ? "__kmpc_for_static_init_8"
2309 : "__kmpc_for_static_init_8u");
2310 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2311 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002312 llvm::Type *TypeParams[] = {
2313 getIdentTyPointerTy(), // loc
2314 CGM.Int32Ty, // tid
2315 CGM.Int32Ty, // schedtype
2316 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2317 PtrTy, // p_lower
2318 PtrTy, // p_upper
2319 PtrTy, // p_stride
2320 ITy, // incr
2321 ITy // chunk
2322 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002323 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002324 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2325 return CGM.CreateRuntimeFunction(FnTy, Name);
2326}
2327
Alexander Musman92bdaab2015-03-12 13:37:50 +00002328llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2329 bool IVSigned) {
2330 assert((IVSize == 32 || IVSize == 64) &&
2331 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002332 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002333 IVSize == 32
2334 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2335 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002336 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002337 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2338 CGM.Int32Ty, // tid
2339 CGM.Int32Ty, // schedtype
2340 ITy, // lower
2341 ITy, // upper
2342 ITy, // stride
2343 ITy // chunk
2344 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002345 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002346 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2347 return CGM.CreateRuntimeFunction(FnTy, Name);
2348}
2349
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002350llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2351 bool IVSigned) {
2352 assert((IVSize == 32 || IVSize == 64) &&
2353 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002354 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002355 IVSize == 32
2356 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2357 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2358 llvm::Type *TypeParams[] = {
2359 getIdentTyPointerTy(), // loc
2360 CGM.Int32Ty, // tid
2361 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002362 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002363 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2364 return CGM.CreateRuntimeFunction(FnTy, Name);
2365}
2366
Alexander Musman92bdaab2015-03-12 13:37:50 +00002367llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2368 bool IVSigned) {
2369 assert((IVSize == 32 || IVSize == 64) &&
2370 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002371 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002372 IVSize == 32
2373 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2374 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002375 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2376 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002377 llvm::Type *TypeParams[] = {
2378 getIdentTyPointerTy(), // loc
2379 CGM.Int32Ty, // tid
2380 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2381 PtrTy, // p_lower
2382 PtrTy, // p_upper
2383 PtrTy // p_stride
2384 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002385 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002386 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2387 return CGM.CreateRuntimeFunction(FnTy, Name);
2388}
2389
Alexey Bataev03f270c2018-03-30 18:31:07 +00002390Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2391 if (CGM.getLangOpts().OpenMPSimd)
2392 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002393 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002394 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002395 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2396 SmallString<64> PtrName;
2397 {
2398 llvm::raw_svector_ostream OS(PtrName);
2399 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2400 }
2401 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2402 if (!Ptr) {
2403 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2404 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2405 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002406 if (!CGM.getLangOpts().OpenMPIsDevice) {
2407 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2408 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2409 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2410 }
2411 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2412 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002413 }
2414 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2415 }
2416 return Address::invalid();
2417}
2418
Alexey Bataev97720002014-11-11 04:05:39 +00002419llvm::Constant *
2420CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002421 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2422 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002423 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002424 std::string Suffix = getName({"cache", ""});
2425 return getOrCreateInternalVariable(
2426 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002427}
2428
John McCall7f416cc2015-09-08 08:05:57 +00002429Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2430 const VarDecl *VD,
2431 Address VDAddr,
2432 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002433 if (CGM.getLangOpts().OpenMPUseTLS &&
2434 CGM.getContext().getTargetInfo().isTLSSupported())
2435 return VDAddr;
2436
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002437 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002438 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002439 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2440 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002441 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2442 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002443 return Address(CGF.EmitRuntimeCall(
2444 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2445 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002446}
2447
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002448void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002449 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002450 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2451 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2452 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002453 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002454 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002455 OMPLoc);
2456 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2457 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002458 llvm::Value *Args[] = {
2459 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2460 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002461 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002462 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002463}
2464
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002465llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002466 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002467 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002468 if (CGM.getLangOpts().OpenMPUseTLS &&
2469 CGM.getContext().getTargetInfo().isTLSSupported())
2470 return nullptr;
2471
Alexey Bataev97720002014-11-11 04:05:39 +00002472 VD = VD->getDefinition(CGM.getContext());
2473 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2474 ThreadPrivateWithDefinition.insert(VD);
2475 QualType ASTTy = VD->getType();
2476
2477 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002478 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002479 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2480 // Generate function that re-emits the declaration's initializer into the
2481 // threadprivate copy of the variable VD
2482 CodeGenFunction CtorCGF(CGM);
2483 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002484 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2485 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002486 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002487 Args.push_back(&Dst);
2488
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002489 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002490 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002491 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002492 std::string Name = getName({"__kmpc_global_ctor_", ""});
2493 llvm::Function *Fn =
2494 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002495 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002496 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002497 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002498 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002499 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002500 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002501 Arg = CtorCGF.Builder.CreateElementBitCast(
2502 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002503 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2504 /*IsInitializer=*/true);
2505 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002506 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002507 CGM.getContext().VoidPtrTy, Dst.getLocation());
2508 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2509 CtorCGF.FinishFunction();
2510 Ctor = Fn;
2511 }
2512 if (VD->getType().isDestructedType() != QualType::DK_none) {
2513 // Generate function that emits destructor call for the threadprivate copy
2514 // of the variable VD
2515 CodeGenFunction DtorCGF(CGM);
2516 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002517 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2518 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002519 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002520 Args.push_back(&Dst);
2521
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002522 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002523 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002524 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002525 std::string Name = getName({"__kmpc_global_dtor_", ""});
2526 llvm::Function *Fn =
2527 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002528 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002529 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002530 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002531 // Create a scope with an artificial location for the body of this function.
2532 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002533 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002534 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002535 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2536 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002537 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2538 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2539 DtorCGF.FinishFunction();
2540 Dtor = Fn;
2541 }
2542 // Do not emit init function if it is not required.
2543 if (!Ctor && !Dtor)
2544 return nullptr;
2545
2546 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002547 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2548 /*isVarArg=*/false)
2549 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002550 // Copying constructor for the threadprivate variable.
2551 // Must be NULL - reserved by runtime, but currently it requires that this
2552 // parameter is always NULL. Otherwise it fires assertion.
2553 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2554 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002555 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2556 /*isVarArg=*/false)
2557 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002558 Ctor = llvm::Constant::getNullValue(CtorTy);
2559 }
2560 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002561 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2562 /*isVarArg=*/false)
2563 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002564 Dtor = llvm::Constant::getNullValue(DtorTy);
2565 }
2566 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002567 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002568 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002569 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002570 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002571 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002572 CodeGenFunction InitCGF(CGM);
2573 FunctionArgList ArgList;
2574 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2575 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002576 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002577 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002578 InitCGF.FinishFunction();
2579 return InitFunction;
2580 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002581 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002582 }
2583 return nullptr;
2584}
2585
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002586/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002587/// consists of the file and device IDs as well as line number associated with
2588/// the relevant entry source location.
2589static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2590 unsigned &DeviceID, unsigned &FileID,
2591 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002592 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002593
2594 // The loc should be always valid and have a file ID (the user cannot use
2595 // #pragma directives in macros)
2596
2597 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002598
2599 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2600 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2601
2602 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002603 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2604 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2605 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002606
2607 DeviceID = ID.getDevice();
2608 FileID = ID.getFile();
2609 LineNum = PLoc.getLine();
2610}
2611
2612bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2613 llvm::GlobalVariable *Addr,
2614 bool PerformInit) {
2615 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002616 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002617 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
Alexey Bataevd01b7492018-08-15 19:45:12 +00002618 return CGM.getLangOpts().OpenMPIsDevice;
Alexey Bataev34f8a702018-03-28 14:28:54 +00002619 VD = VD->getDefinition(CGM.getContext());
2620 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2621 return CGM.getLangOpts().OpenMPIsDevice;
2622
2623 QualType ASTTy = VD->getType();
2624
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002625 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002626 // Produce the unique prefix to identify the new target regions. We use
2627 // the source location of the variable declaration which we know to not
2628 // conflict with any target region.
2629 unsigned DeviceID;
2630 unsigned FileID;
2631 unsigned Line;
2632 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2633 SmallString<128> Buffer, Out;
2634 {
2635 llvm::raw_svector_ostream OS(Buffer);
2636 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2637 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2638 }
2639
2640 const Expr *Init = VD->getAnyInitializer();
2641 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2642 llvm::Constant *Ctor;
2643 llvm::Constant *ID;
2644 if (CGM.getLangOpts().OpenMPIsDevice) {
2645 // Generate function that re-emits the declaration's initializer into
2646 // the threadprivate copy of the variable VD
2647 CodeGenFunction CtorCGF(CGM);
2648
2649 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2650 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2651 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2652 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2653 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2654 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2655 FunctionArgList(), Loc, Loc);
2656 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2657 CtorCGF.EmitAnyExprToMem(Init,
2658 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2659 Init->getType().getQualifiers(),
2660 /*IsInitializer=*/true);
2661 CtorCGF.FinishFunction();
2662 Ctor = Fn;
2663 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002664 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002665 } else {
2666 Ctor = new llvm::GlobalVariable(
2667 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2668 llvm::GlobalValue::PrivateLinkage,
2669 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2670 ID = Ctor;
2671 }
2672
2673 // Register the information for the entry associated with the constructor.
2674 Out.clear();
2675 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2676 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002677 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002678 }
2679 if (VD->getType().isDestructedType() != QualType::DK_none) {
2680 llvm::Constant *Dtor;
2681 llvm::Constant *ID;
2682 if (CGM.getLangOpts().OpenMPIsDevice) {
2683 // Generate function that emits destructor call for the threadprivate
2684 // copy of the variable VD
2685 CodeGenFunction DtorCGF(CGM);
2686
2687 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2688 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2689 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2690 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2691 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2692 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2693 FunctionArgList(), Loc, Loc);
2694 // Create a scope with an artificial location for the body of this
2695 // function.
2696 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2697 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2698 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2699 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2700 DtorCGF.FinishFunction();
2701 Dtor = Fn;
2702 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002703 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002704 } else {
2705 Dtor = new llvm::GlobalVariable(
2706 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2707 llvm::GlobalValue::PrivateLinkage,
2708 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2709 ID = Dtor;
2710 }
2711 // Register the information for the entry associated with the destructor.
2712 Out.clear();
2713 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2714 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002715 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002716 }
2717 return CGM.getLangOpts().OpenMPIsDevice;
2718}
2719
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002720Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2721 QualType VarType,
2722 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002723 std::string Suffix = getName({"artificial", ""});
2724 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002725 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002726 llvm::Value *GAddr =
2727 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002728 llvm::Value *Args[] = {
2729 emitUpdateLocation(CGF, SourceLocation()),
2730 getThreadID(CGF, SourceLocation()),
2731 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2732 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2733 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002734 getOrCreateInternalVariable(
2735 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002736 return Address(
2737 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2738 CGF.EmitRuntimeCall(
2739 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2740 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2741 CGM.getPointerAlign());
2742}
2743
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002744void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2745 const RegionCodeGenTy &ThenGen,
2746 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002747 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2748
2749 // If the condition constant folds and can be elided, try to avoid emitting
2750 // the condition and the dead arm of the if/else.
2751 bool CondConstant;
2752 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002753 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002754 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002755 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002756 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002757 return;
2758 }
2759
2760 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2761 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002762 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2763 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2764 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002765 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2766
2767 // Emit the 'then' code.
2768 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002769 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002770 CGF.EmitBranch(ContBlock);
2771 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002772 // There is no need to emit line number for unconditional branch.
2773 (void)ApplyDebugLocation::CreateEmpty(CGF);
2774 CGF.EmitBlock(ElseBlock);
2775 ElseGen(CGF);
2776 // There is no need to emit line number for unconditional branch.
2777 (void)ApplyDebugLocation::CreateEmpty(CGF);
2778 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002779 // Emit the continuation block for code after the if.
2780 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002781}
2782
Alexey Bataev1d677132015-04-22 13:57:31 +00002783void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2784 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002785 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002786 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002787 if (!CGF.HaveInsertPoint())
2788 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002789 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002790 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2791 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002792 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002793 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002794 llvm::Value *Args[] = {
2795 RTLoc,
2796 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002797 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002798 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2799 RealArgs.append(std::begin(Args), std::end(Args));
2800 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2801
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002802 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002803 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2804 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002805 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2806 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002807 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2808 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002809 // Build calls:
2810 // __kmpc_serialized_parallel(&Loc, GTid);
2811 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002812 CGF.EmitRuntimeCall(
2813 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002814
Alexey Bataev1d677132015-04-22 13:57:31 +00002815 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002816 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2817 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002818 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002819 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataev8521ff62018-07-25 20:03:01 +00002820 // ThreadId for serialized parallels is 0.
2821 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002822 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2823 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002824 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002825
Alexey Bataev1d677132015-04-22 13:57:31 +00002826 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002827 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002828 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002829 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2830 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002831 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002832 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002833 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002834 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002835 RegionCodeGenTy ThenRCG(ThenGen);
2836 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002837 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002838}
2839
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002840// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002841// thread-ID variable (it is passed in a first argument of the outlined function
2842// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2843// regular serial code region, get thread ID by calling kmp_int32
2844// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2845// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002846Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2847 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002848 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002849 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002850 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002851 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002852
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002853 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2854 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002855 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002856 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002857 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002858 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002859
2860 return ThreadIDTemp;
2861}
2862
Alexey Bataev97720002014-11-11 04:05:39 +00002863llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002864CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002865 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002866 SmallString<256> Buffer;
2867 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002868 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002869 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002870 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002871 if (Elem.second) {
2872 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002873 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002874 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002875 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002876
David Blaikie13156b62014-11-19 03:06:06 +00002877 return Elem.second = new llvm::GlobalVariable(
2878 CGM.getModule(), Ty, /*IsConstant*/ false,
2879 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2880 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002881}
2882
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002883llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002884 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2885 std::string Name = getName({Prefix, "var"});
2886 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002887}
2888
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002889namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002890/// Common pre(post)-action for different OpenMP constructs.
2891class CommonActionTy final : public PrePostActionTy {
2892 llvm::Value *EnterCallee;
2893 ArrayRef<llvm::Value *> EnterArgs;
2894 llvm::Value *ExitCallee;
2895 ArrayRef<llvm::Value *> ExitArgs;
2896 bool Conditional;
2897 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002898
2899public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002900 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2901 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2902 bool Conditional = false)
2903 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2904 ExitArgs(ExitArgs), Conditional(Conditional) {}
2905 void Enter(CodeGenFunction &CGF) override {
2906 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2907 if (Conditional) {
2908 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2909 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2910 ContBlock = CGF.createBasicBlock("omp_if.end");
2911 // Generate the branch (If-stmt)
2912 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2913 CGF.EmitBlock(ThenBlock);
2914 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002915 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002916 void Done(CodeGenFunction &CGF) {
2917 // Emit the rest of blocks/branches
2918 CGF.EmitBranch(ContBlock);
2919 CGF.EmitBlock(ContBlock, true);
2920 }
2921 void Exit(CodeGenFunction &CGF) override {
2922 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002923 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002924};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002925} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002926
2927void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2928 StringRef CriticalName,
2929 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002930 SourceLocation Loc, const Expr *Hint) {
2931 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002932 // CriticalOpGen();
2933 // __kmpc_end_critical(ident_t *, gtid, Lock);
2934 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002935 if (!CGF.HaveInsertPoint())
2936 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002937 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2938 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002939 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2940 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002941 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002942 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2943 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2944 }
2945 CommonActionTy Action(
2946 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2947 : OMPRTL__kmpc_critical),
2948 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2949 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002950 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002951}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002952
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002953void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002954 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002955 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002956 if (!CGF.HaveInsertPoint())
2957 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002958 // if(__kmpc_master(ident_t *, gtid)) {
2959 // MasterOpGen();
2960 // __kmpc_end_master(ident_t *, gtid);
2961 // }
2962 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002963 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002964 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2965 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2966 /*Conditional=*/true);
2967 MasterOpGen.setAction(Action);
2968 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2969 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002970}
2971
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002972void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2973 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002974 if (!CGF.HaveInsertPoint())
2975 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002976 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2977 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002978 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002979 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002980 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002981 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2982 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002983}
2984
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002985void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2986 const RegionCodeGenTy &TaskgroupOpGen,
2987 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002988 if (!CGF.HaveInsertPoint())
2989 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002990 // __kmpc_taskgroup(ident_t *, gtid);
2991 // TaskgroupOpGen();
2992 // __kmpc_end_taskgroup(ident_t *, gtid);
2993 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002994 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2995 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2996 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2997 Args);
2998 TaskgroupOpGen.setAction(Action);
2999 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003000}
3001
John McCall7f416cc2015-09-08 08:05:57 +00003002/// Given an array of pointers to variables, project the address of a
3003/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003004static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3005 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003006 // Pull out the pointer to the variable.
3007 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003008 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003009 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3010
3011 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003012 Addr = CGF.Builder.CreateElementBitCast(
3013 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003014 return Addr;
3015}
3016
Alexey Bataeva63048e2015-03-23 06:18:07 +00003017static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003018 CodeGenModule &CGM, llvm::Type *ArgsType,
3019 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003020 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3021 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003022 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003023 // void copy_func(void *LHSArg, void *RHSArg);
3024 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003025 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3026 ImplicitParamDecl::Other);
3027 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3028 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003029 Args.push_back(&LHSArg);
3030 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003031 const auto &CGFI =
3032 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003033 std::string Name =
3034 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3035 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3036 llvm::GlobalValue::InternalLinkage, Name,
3037 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003038 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003039 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003040 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003041 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003042 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003043 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003044 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3045 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3046 ArgsType), CGF.getPointerAlign());
3047 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3048 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3049 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003050 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3051 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3052 // ...
3053 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003054 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003055 const auto *DestVar =
3056 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003057 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3058
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003059 const auto *SrcVar =
3060 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003061 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3062
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003063 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003064 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003065 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003066 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003067 CGF.FinishFunction();
3068 return Fn;
3069}
3070
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003071void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003072 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003073 SourceLocation Loc,
3074 ArrayRef<const Expr *> CopyprivateVars,
3075 ArrayRef<const Expr *> SrcExprs,
3076 ArrayRef<const Expr *> DstExprs,
3077 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003078 if (!CGF.HaveInsertPoint())
3079 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003080 assert(CopyprivateVars.size() == SrcExprs.size() &&
3081 CopyprivateVars.size() == DstExprs.size() &&
3082 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003083 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003084 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003085 // if(__kmpc_single(ident_t *, gtid)) {
3086 // SingleOpGen();
3087 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003088 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003089 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003090 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3091 // <copy_func>, did_it);
3092
John McCall7f416cc2015-09-08 08:05:57 +00003093 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003094 if (!CopyprivateVars.empty()) {
3095 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003096 QualType KmpInt32Ty =
3097 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003098 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003099 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003100 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003101 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003102 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003103 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3104 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3105 /*Conditional=*/true);
3106 SingleOpGen.setAction(Action);
3107 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3108 if (DidIt.isValid()) {
3109 // did_it = 1;
3110 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3111 }
3112 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003113 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3114 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003115 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003116 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003117 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003118 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3119 /*IndexTypeQuals=*/0);
3120 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003121 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003122 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3123 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003124 Address Elem = CGF.Builder.CreateConstArrayGEP(
3125 CopyprivateList, I, CGF.getPointerSize());
3126 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003127 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003128 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3129 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003130 }
3131 // Build function that copies private values from single region to all other
3132 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003133 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003134 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003135 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003136 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003137 Address CL =
3138 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3139 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003140 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003141 llvm::Value *Args[] = {
3142 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3143 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003144 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003145 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003146 CpyFn, // void (*) (void *, void *) <copy_func>
3147 DidItVal // i32 did_it
3148 };
3149 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3150 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003151}
3152
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003153void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3154 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003155 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003156 if (!CGF.HaveInsertPoint())
3157 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003158 // __kmpc_ordered(ident_t *, gtid);
3159 // OrderedOpGen();
3160 // __kmpc_end_ordered(ident_t *, gtid);
3161 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003162 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003163 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003164 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3165 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3166 Args);
3167 OrderedOpGen.setAction(Action);
3168 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3169 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003170 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003171 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003172}
3173
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003174void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003175 OpenMPDirectiveKind Kind, bool EmitChecks,
3176 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003177 if (!CGF.HaveInsertPoint())
3178 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003179 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003180 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003181 unsigned Flags;
3182 if (Kind == OMPD_for)
3183 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3184 else if (Kind == OMPD_sections)
3185 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3186 else if (Kind == OMPD_single)
3187 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3188 else if (Kind == OMPD_barrier)
3189 Flags = OMP_IDENT_BARRIER_EXPL;
3190 else
3191 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003192 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3193 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003194 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3195 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003196 if (auto *OMPRegionInfo =
3197 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003198 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003199 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003200 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003201 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003202 // if (__kmpc_cancel_barrier()) {
3203 // exit from construct;
3204 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003205 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3206 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3207 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003208 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3209 CGF.EmitBlock(ExitBB);
3210 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003211 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003212 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003213 CGF.EmitBranchThroughCleanup(CancelDestination);
3214 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3215 }
3216 return;
3217 }
3218 }
3219 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003220}
3221
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003222/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003223static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003224 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003225 switch (ScheduleKind) {
3226 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003227 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3228 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003229 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003230 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003231 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003232 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003233 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003234 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3235 case OMPC_SCHEDULE_auto:
3236 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003237 case OMPC_SCHEDULE_unknown:
3238 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003239 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003240 }
3241 llvm_unreachable("Unexpected runtime schedule");
3242}
3243
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003244/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003245static OpenMPSchedType
3246getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3247 // only static is allowed for dist_schedule
3248 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3249}
3250
Alexander Musmanc6388682014-12-15 07:07:06 +00003251bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3252 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003253 OpenMPSchedType Schedule =
3254 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003255 return Schedule == OMP_sch_static;
3256}
3257
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003258bool CGOpenMPRuntime::isStaticNonchunked(
3259 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003260 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003261 return Schedule == OMP_dist_sch_static;
3262}
3263
3264
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003265bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003266 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003267 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003268 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3269 return Schedule != OMP_sch_static;
3270}
3271
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003272static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3273 OpenMPScheduleClauseModifier M1,
3274 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003275 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003276 switch (M1) {
3277 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003278 Modifier = OMP_sch_modifier_monotonic;
3279 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003280 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003281 Modifier = OMP_sch_modifier_nonmonotonic;
3282 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003283 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003284 if (Schedule == OMP_sch_static_chunked)
3285 Schedule = OMP_sch_static_balanced_chunked;
3286 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003287 case OMPC_SCHEDULE_MODIFIER_last:
3288 case OMPC_SCHEDULE_MODIFIER_unknown:
3289 break;
3290 }
3291 switch (M2) {
3292 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003293 Modifier = OMP_sch_modifier_monotonic;
3294 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003295 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003296 Modifier = OMP_sch_modifier_nonmonotonic;
3297 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003298 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003299 if (Schedule == OMP_sch_static_chunked)
3300 Schedule = OMP_sch_static_balanced_chunked;
3301 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003302 case OMPC_SCHEDULE_MODIFIER_last:
3303 case OMPC_SCHEDULE_MODIFIER_unknown:
3304 break;
3305 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003306 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003307}
3308
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003309void CGOpenMPRuntime::emitForDispatchInit(
3310 CodeGenFunction &CGF, SourceLocation Loc,
3311 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3312 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003313 if (!CGF.HaveInsertPoint())
3314 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003315 OpenMPSchedType Schedule = getRuntimeSchedule(
3316 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003317 assert(Ordered ||
3318 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003319 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3320 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003321 // Call __kmpc_dispatch_init(
3322 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3323 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3324 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003325
John McCall7f416cc2015-09-08 08:05:57 +00003326 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003327 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3328 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003329 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003330 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3331 CGF.Builder.getInt32(addMonoNonMonoModifier(
3332 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003333 DispatchValues.LB, // Lower
3334 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003335 CGF.Builder.getIntN(IVSize, 1), // Stride
3336 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003337 };
3338 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3339}
3340
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003341static void emitForStaticInitCall(
3342 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3343 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3344 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003345 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003346 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003347 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003348
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003349 assert(!Values.Ordered);
3350 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3351 Schedule == OMP_sch_static_balanced_chunked ||
3352 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3353 Schedule == OMP_dist_sch_static ||
3354 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003355
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003356 // Call __kmpc_for_static_init(
3357 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3358 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3359 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3360 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3361 llvm::Value *Chunk = Values.Chunk;
3362 if (Chunk == nullptr) {
3363 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3364 Schedule == OMP_dist_sch_static) &&
3365 "expected static non-chunked schedule");
3366 // If the Chunk was not specified in the clause - use default value 1.
3367 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3368 } else {
3369 assert((Schedule == OMP_sch_static_chunked ||
3370 Schedule == OMP_sch_static_balanced_chunked ||
3371 Schedule == OMP_ord_static_chunked ||
3372 Schedule == OMP_dist_sch_static_chunked) &&
3373 "expected static chunked schedule");
3374 }
3375 llvm::Value *Args[] = {
3376 UpdateLocation,
3377 ThreadId,
3378 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3379 M2)), // Schedule type
3380 Values.IL.getPointer(), // &isLastIter
3381 Values.LB.getPointer(), // &LB
3382 Values.UB.getPointer(), // &UB
3383 Values.ST.getPointer(), // &Stride
3384 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3385 Chunk // Chunk
3386 };
3387 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003388}
3389
John McCall7f416cc2015-09-08 08:05:57 +00003390void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3391 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003392 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003393 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003394 const StaticRTInput &Values) {
3395 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3396 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3397 assert(isOpenMPWorksharingDirective(DKind) &&
3398 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003399 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003400 isOpenMPLoopDirective(DKind)
3401 ? OMP_IDENT_WORK_LOOP
3402 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003403 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3404 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003405 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003406 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003407 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003408}
John McCall7f416cc2015-09-08 08:05:57 +00003409
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003410void CGOpenMPRuntime::emitDistributeStaticInit(
3411 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003412 OpenMPDistScheduleClauseKind SchedKind,
3413 const CGOpenMPRuntime::StaticRTInput &Values) {
3414 OpenMPSchedType ScheduleNum =
3415 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003416 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003417 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003418 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3419 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003420 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003421 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3422 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003423 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003424}
3425
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003426void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003427 SourceLocation Loc,
3428 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003429 if (!CGF.HaveInsertPoint())
3430 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003431 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003432 llvm::Value *Args[] = {
3433 emitUpdateLocation(CGF, Loc,
3434 isOpenMPDistributeDirective(DKind)
3435 ? OMP_IDENT_WORK_DISTRIBUTE
3436 : isOpenMPLoopDirective(DKind)
3437 ? OMP_IDENT_WORK_LOOP
3438 : OMP_IDENT_WORK_SECTIONS),
3439 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003440 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3441 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003442}
3443
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003444void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3445 SourceLocation Loc,
3446 unsigned IVSize,
3447 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003448 if (!CGF.HaveInsertPoint())
3449 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003450 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003451 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003452 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3453}
3454
Alexander Musman92bdaab2015-03-12 13:37:50 +00003455llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3456 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003457 bool IVSigned, Address IL,
3458 Address LB, Address UB,
3459 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003460 // Call __kmpc_dispatch_next(
3461 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3462 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3463 // kmp_int[32|64] *p_stride);
3464 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003465 emitUpdateLocation(CGF, Loc),
3466 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003467 IL.getPointer(), // &isLastIter
3468 LB.getPointer(), // &Lower
3469 UB.getPointer(), // &Upper
3470 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003471 };
3472 llvm::Value *Call =
3473 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3474 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003475 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003476 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003477}
3478
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003479void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3480 llvm::Value *NumThreads,
3481 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003482 if (!CGF.HaveInsertPoint())
3483 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003484 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3485 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003486 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003487 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003488 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3489 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003490}
3491
Alexey Bataev7f210c62015-06-18 13:40:03 +00003492void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3493 OpenMPProcBindClauseKind ProcBind,
3494 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003495 if (!CGF.HaveInsertPoint())
3496 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003497 // Constants for proc bind value accepted by the runtime.
3498 enum ProcBindTy {
3499 ProcBindFalse = 0,
3500 ProcBindTrue,
3501 ProcBindMaster,
3502 ProcBindClose,
3503 ProcBindSpread,
3504 ProcBindIntel,
3505 ProcBindDefault
3506 } RuntimeProcBind;
3507 switch (ProcBind) {
3508 case OMPC_PROC_BIND_master:
3509 RuntimeProcBind = ProcBindMaster;
3510 break;
3511 case OMPC_PROC_BIND_close:
3512 RuntimeProcBind = ProcBindClose;
3513 break;
3514 case OMPC_PROC_BIND_spread:
3515 RuntimeProcBind = ProcBindSpread;
3516 break;
3517 case OMPC_PROC_BIND_unknown:
3518 llvm_unreachable("Unsupported proc_bind value.");
3519 }
3520 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3521 llvm::Value *Args[] = {
3522 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3523 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3524 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3525}
3526
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003527void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3528 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003529 if (!CGF.HaveInsertPoint())
3530 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003531 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003532 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3533 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003534}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003535
Alexey Bataev62b63b12015-03-10 07:28:44 +00003536namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003537/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003538enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003539 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003540 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003541 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003542 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003543 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003544 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003545 /// Function with call of destructors for private variables.
3546 Data1,
3547 /// Task priority.
3548 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003549 /// (Taskloops only) Lower bound.
3550 KmpTaskTLowerBound,
3551 /// (Taskloops only) Upper bound.
3552 KmpTaskTUpperBound,
3553 /// (Taskloops only) Stride.
3554 KmpTaskTStride,
3555 /// (Taskloops only) Is last iteration flag.
3556 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003557 /// (Taskloops only) Reduction data.
3558 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003559};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003560} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003561
Samuel Antaoee8fb302016-01-06 13:42:12 +00003562bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003563 return OffloadEntriesTargetRegion.empty() &&
3564 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003565}
3566
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003567/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003568void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3569 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3570 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003571 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003572 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3573 "only required for the device "
3574 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003575 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003576 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003577 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003578 ++OffloadingEntriesNum;
3579}
3580
3581void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3582 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3583 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003584 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003585 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003586 // If we are emitting code for a target, the entry is already initialized,
3587 // only has to be registered.
3588 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003589 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3590 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3591 DiagnosticsEngine::Error,
3592 "Unable to find target region on line '%0' in the device code.");
3593 CGM.getDiags().Report(DiagID) << LineNum;
3594 return;
3595 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003596 auto &Entry =
3597 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003598 assert(Entry.isValid() && "Entry not initialized!");
3599 Entry.setAddress(Addr);
3600 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003601 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003602 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003603 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003604 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003605 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003606 }
3607}
3608
3609bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003610 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3611 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003612 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3613 if (PerDevice == OffloadEntriesTargetRegion.end())
3614 return false;
3615 auto PerFile = PerDevice->second.find(FileID);
3616 if (PerFile == PerDevice->second.end())
3617 return false;
3618 auto PerParentName = PerFile->second.find(ParentName);
3619 if (PerParentName == PerFile->second.end())
3620 return false;
3621 auto PerLine = PerParentName->second.find(LineNum);
3622 if (PerLine == PerParentName->second.end())
3623 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003624 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003625 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003626 return false;
3627 return true;
3628}
3629
3630void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3631 const OffloadTargetRegionEntryInfoActTy &Action) {
3632 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003633 for (const auto &D : OffloadEntriesTargetRegion)
3634 for (const auto &F : D.second)
3635 for (const auto &P : F.second)
3636 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003637 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003638}
3639
Alexey Bataev03f270c2018-03-30 18:31:07 +00003640void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3641 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3642 OMPTargetGlobalVarEntryKind Flags,
3643 unsigned Order) {
3644 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3645 "only required for the device "
3646 "code generation.");
3647 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3648 ++OffloadingEntriesNum;
3649}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003650
Alexey Bataev03f270c2018-03-30 18:31:07 +00003651void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3652 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3653 CharUnits VarSize,
3654 OMPTargetGlobalVarEntryKind Flags,
3655 llvm::GlobalValue::LinkageTypes Linkage) {
3656 if (CGM.getLangOpts().OpenMPIsDevice) {
3657 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3658 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3659 "Entry not initialized!");
3660 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3661 "Resetting with the new address.");
3662 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3663 return;
3664 Entry.setAddress(Addr);
3665 Entry.setVarSize(VarSize);
3666 Entry.setLinkage(Linkage);
3667 } else {
3668 if (hasDeviceGlobalVarEntryInfo(VarName))
3669 return;
3670 OffloadEntriesDeviceGlobalVar.try_emplace(
3671 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3672 ++OffloadingEntriesNum;
3673 }
3674}
3675
3676void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3677 actOnDeviceGlobalVarEntriesInfo(
3678 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3679 // Scan all target region entries and perform the provided action.
3680 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3681 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003682}
3683
3684llvm::Function *
3685CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003686 // If we don't have entries or if we are emitting code for the device, we
3687 // don't need to do anything.
3688 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3689 return nullptr;
3690
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003691 llvm::Module &M = CGM.getModule();
3692 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003693
3694 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003695 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003696
3697 // We should be creating an offloading descriptor only if there are devices
3698 // specified.
3699 assert(!Devices.empty() && "No OpenMP offloading devices??");
3700
3701 // Create the external variables that will point to the begin and end of the
3702 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003703 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003704 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003705 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003706 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003707 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003708 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003709 EntriesBeginName);
3710 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3711 auto *HostEntriesEnd =
3712 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3713 llvm::GlobalValue::ExternalLinkage,
3714 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003715
3716 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003717 auto *DeviceImageTy = cast<llvm::StructType>(
3718 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003719 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003720 ConstantArrayBuilder DeviceImagesEntries =
3721 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003722
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003723 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003724 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003725 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003726 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003727 M, CGM.Int8Ty, /*isConstant=*/true,
3728 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003729 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3730 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003731 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003732 M, CGM.Int8Ty, /*isConstant=*/true,
3733 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003734 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003735
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003736 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3737 HostEntriesEnd};
3738 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3739 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003740 }
3741
3742 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003743 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003744 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003745 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3746 CGM.getPointerAlign(),
3747 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003748 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003749
3750 // This is a Zero array to be used in the creation of the constant expressions
3751 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3752 llvm::Constant::getNullValue(CGM.Int32Ty)};
3753
3754 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003755 llvm::Constant *Data[] = {
3756 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3757 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3758 DeviceImages, Index),
3759 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003760 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003761 llvm::GlobalVariable *Desc = createGlobalStruct(
3762 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003763
3764 // Emit code to register or unregister the descriptor at execution
3765 // startup or closing, respectively.
3766
Alexey Bataev03f270c2018-03-30 18:31:07 +00003767 llvm::Function *UnRegFn;
3768 {
3769 FunctionArgList Args;
3770 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3771 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003772
Alexey Bataev03f270c2018-03-30 18:31:07 +00003773 CodeGenFunction CGF(CGM);
3774 // Disable debug info for global (de-)initializer because they are not part
3775 // of some particular construct.
3776 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003777 const auto &FI =
3778 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3779 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003780 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3781 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003782 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3783 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3784 Desc);
3785 CGF.FinishFunction();
3786 }
3787 llvm::Function *RegFn;
3788 {
3789 CodeGenFunction CGF(CGM);
3790 // Disable debug info for global (de-)initializer because they are not part
3791 // of some particular construct.
3792 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003793 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003794 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003795
3796 // Encode offload target triples into the registration function name. It
3797 // will serve as a comdat key for the registration/unregistration code for
3798 // this particular combination of offloading targets.
3799 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3800 RegFnNameParts[0] = "omp_offloading";
3801 RegFnNameParts[1] = "descriptor_reg";
3802 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3803 [](const llvm::Triple &T) -> const std::string& {
3804 return T.getTriple();
3805 });
3806 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3807 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003808 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003809 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3810 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3811 // Create a variable to drive the registration and unregistration of the
3812 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3813 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3814 SourceLocation(), nullptr, C.CharTy,
3815 ImplicitParamDecl::Other);
3816 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3817 CGF.FinishFunction();
3818 }
George Rokos29d0f002017-05-27 03:03:13 +00003819 if (CGM.supportsCOMDAT()) {
3820 // It is sufficient to call registration function only once, so create a
3821 // COMDAT group for registration/unregistration functions and associated
3822 // data. That would reduce startup time and code size. Registration
3823 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003824 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003825 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3826 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3827 RegFn->setComdat(ComdatKey);
3828 UnRegFn->setComdat(ComdatKey);
3829 DeviceImages->setComdat(ComdatKey);
3830 Desc->setComdat(ComdatKey);
3831 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003832 return RegFn;
3833}
3834
Alexey Bataev03f270c2018-03-30 18:31:07 +00003835void CGOpenMPRuntime::createOffloadEntry(
3836 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3837 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003838 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003839 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003840 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003841
3842 // Create constant string with the name.
3843 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3844
Alexey Bataev18fa2322018-05-02 14:20:50 +00003845 std::string StringName = getName({"omp_offloading", "entry_name"});
3846 auto *Str = new llvm::GlobalVariable(
3847 M, StrPtrInit->getType(), /*isConstant=*/true,
3848 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003849 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003850
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003851 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3852 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3853 llvm::ConstantInt::get(CGM.SizeTy, Size),
3854 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3855 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003856 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003857 llvm::GlobalVariable *Entry = createGlobalStruct(
3858 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3859 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003860
3861 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003862 std::string Section = getName({"omp_offloading", "entries"});
3863 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003864}
3865
3866void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3867 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003868 // can easily figure out what to emit. The produced metadata looks like
3869 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003870 //
3871 // !omp_offload.info = !{!1, ...}
3872 //
3873 // Right now we only generate metadata for function that contain target
3874 // regions.
3875
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003876 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003877 if (OffloadEntriesInfoManager.empty())
3878 return;
3879
3880 llvm::Module &M = CGM.getModule();
3881 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003882 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003883 OrderedEntries(OffloadEntriesInfoManager.size());
3884
Simon Pilgrim2c518802017-03-30 14:13:19 +00003885 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003886 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003887 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003888 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003889 };
3890
Alexey Bataev03f270c2018-03-30 18:31:07 +00003891 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3892
3893 // Create the offloading info metadata node.
3894 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003895
3896 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003897 auto &&TargetRegionMetadataEmitter =
3898 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3899 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3900 unsigned Line,
3901 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3902 // Generate metadata for target regions. Each entry of this metadata
3903 // contains:
3904 // - Entry 0 -> Kind of this type of metadata (0).
3905 // - Entry 1 -> Device ID of the file where the entry was identified.
3906 // - Entry 2 -> File ID of the file where the entry was identified.
3907 // - Entry 3 -> Mangled name of the function where the entry was
3908 // identified.
3909 // - Entry 4 -> Line in the file where the entry was identified.
3910 // - Entry 5 -> Order the entry was created.
3911 // The first element of the metadata node is the kind.
3912 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3913 GetMDInt(FileID), GetMDString(ParentName),
3914 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003915
Alexey Bataev03f270c2018-03-30 18:31:07 +00003916 // Save this entry in the right position of the ordered entries array.
3917 OrderedEntries[E.getOrder()] = &E;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003918
Alexey Bataev03f270c2018-03-30 18:31:07 +00003919 // Add metadata to the named metadata node.
3920 MD->addOperand(llvm::MDNode::get(C, Ops));
3921 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003922
3923 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3924 TargetRegionMetadataEmitter);
3925
Alexey Bataev03f270c2018-03-30 18:31:07 +00003926 // Create function that emits metadata for each device global variable entry;
3927 auto &&DeviceGlobalVarMetadataEmitter =
3928 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3929 MD](StringRef MangledName,
3930 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3931 &E) {
3932 // Generate metadata for global variables. Each entry of this metadata
3933 // contains:
3934 // - Entry 0 -> Kind of this type of metadata (1).
3935 // - Entry 1 -> Mangled name of the variable.
3936 // - Entry 2 -> Declare target kind.
3937 // - Entry 3 -> Order the entry was created.
3938 // The first element of the metadata node is the kind.
3939 llvm::Metadata *Ops[] = {
3940 GetMDInt(E.getKind()), GetMDString(MangledName),
3941 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3942
3943 // Save this entry in the right position of the ordered entries array.
3944 OrderedEntries[E.getOrder()] = &E;
3945
3946 // Add metadata to the named metadata node.
3947 MD->addOperand(llvm::MDNode::get(C, Ops));
3948 };
3949
3950 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3951 DeviceGlobalVarMetadataEmitter);
3952
3953 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003954 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003955 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003956 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3957 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003958 if (!CE->getID() || !CE->getAddress()) {
3959 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3960 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00003961 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003962 "address or the ID is invalid.");
3963 CGM.getDiags().Report(DiagID);
3964 continue;
3965 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00003966 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00003967 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3968 } else if (const auto *CE =
3969 dyn_cast<OffloadEntriesInfoManagerTy::
3970 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00003971 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
3972 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
3973 CE->getFlags());
3974 switch (Flags) {
3975 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
3976 if (!CE->getAddress()) {
3977 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3978 DiagnosticsEngine::Error,
3979 "Offloading entry for declare target variable is incorrect: the "
3980 "address is invalid.");
3981 CGM.getDiags().Report(DiagID);
3982 continue;
3983 }
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00003984 // The vaiable has no definition - no need to add the entry.
3985 if (CE->getVarSize().isZero())
3986 continue;
Alexey Bataevc52f01d2018-07-16 20:05:25 +00003987 break;
3988 }
3989 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
3990 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
3991 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
3992 "Declaret target link address is set.");
3993 if (CGM.getLangOpts().OpenMPIsDevice)
3994 continue;
3995 if (!CE->getAddress()) {
3996 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3997 DiagnosticsEngine::Error,
3998 "Offloading entry for declare target variable is incorrect: the "
3999 "address is invalid.");
4000 CGM.getDiags().Report(DiagID);
4001 continue;
4002 }
4003 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004004 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004005 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004006 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004007 CE->getLinkage());
4008 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004009 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004010 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004011 }
4012}
4013
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004014/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004015/// metadata.
4016void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4017 // If we are in target mode, load the metadata from the host IR. This code has
4018 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4019
4020 if (!CGM.getLangOpts().OpenMPIsDevice)
4021 return;
4022
4023 if (CGM.getLangOpts().OMPHostIRFile.empty())
4024 return;
4025
4026 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004027 if (auto EC = Buf.getError()) {
4028 CGM.getDiags().Report(diag::err_cannot_open_file)
4029 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004030 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004031 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004032
4033 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004034 auto ME = expectedToErrorOrAndEmitErrors(
4035 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004036
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004037 if (auto EC = ME.getError()) {
4038 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4039 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4040 CGM.getDiags().Report(DiagID)
4041 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004042 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004043 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004044
4045 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4046 if (!MD)
4047 return;
4048
George Burgess IV00f70bd2018-03-01 05:43:23 +00004049 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004050 auto &&GetMDInt = [MN](unsigned Idx) {
4051 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004052 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4053 };
4054
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004055 auto &&GetMDString = [MN](unsigned Idx) {
4056 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004057 return V->getString();
4058 };
4059
Alexey Bataev03f270c2018-03-30 18:31:07 +00004060 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004061 default:
4062 llvm_unreachable("Unexpected metadata!");
4063 break;
4064 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004065 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004066 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004067 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4068 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4069 /*Order=*/GetMDInt(5));
4070 break;
4071 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4072 OffloadingEntryInfoDeviceGlobalVar:
4073 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4074 /*MangledName=*/GetMDString(1),
4075 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4076 /*Flags=*/GetMDInt(2)),
4077 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004078 break;
4079 }
4080 }
4081}
4082
Alexey Bataev62b63b12015-03-10 07:28:44 +00004083void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4084 if (!KmpRoutineEntryPtrTy) {
4085 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004086 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004087 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4088 FunctionProtoType::ExtProtoInfo EPI;
4089 KmpRoutineEntryPtrQTy = C.getPointerType(
4090 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4091 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4092 }
4093}
4094
Samuel Antaoee8fb302016-01-06 13:42:12 +00004095QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004096 // Make sure the type of the entry is already created. This is the type we
4097 // have to create:
4098 // struct __tgt_offload_entry{
4099 // void *addr; // Pointer to the offload entry info.
4100 // // (function or global)
4101 // char *name; // Name of the function or global.
4102 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004103 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4104 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004105 // };
4106 if (TgtOffloadEntryQTy.isNull()) {
4107 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004108 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004109 RD->startDefinition();
4110 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4111 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4112 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004113 addFieldToRecordDecl(
4114 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4115 addFieldToRecordDecl(
4116 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004117 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004118 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004119 TgtOffloadEntryQTy = C.getRecordType(RD);
4120 }
4121 return TgtOffloadEntryQTy;
4122}
4123
4124QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4125 // These are the types we need to build:
4126 // struct __tgt_device_image{
4127 // void *ImageStart; // Pointer to the target code start.
4128 // void *ImageEnd; // Pointer to the target code end.
4129 // // We also add the host entries to the device image, as it may be useful
4130 // // for the target runtime to have access to that information.
4131 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4132 // // the entries.
4133 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4134 // // entries (non inclusive).
4135 // };
4136 if (TgtDeviceImageQTy.isNull()) {
4137 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004138 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004139 RD->startDefinition();
4140 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4141 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4142 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4143 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4144 RD->completeDefinition();
4145 TgtDeviceImageQTy = C.getRecordType(RD);
4146 }
4147 return TgtDeviceImageQTy;
4148}
4149
4150QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4151 // struct __tgt_bin_desc{
4152 // int32_t NumDevices; // Number of devices supported.
4153 // __tgt_device_image *DeviceImages; // Arrays of device images
4154 // // (one per device).
4155 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4156 // // entries.
4157 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4158 // // entries (non inclusive).
4159 // };
4160 if (TgtBinaryDescriptorQTy.isNull()) {
4161 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004162 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004163 RD->startDefinition();
4164 addFieldToRecordDecl(
4165 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4166 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4167 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4168 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4169 RD->completeDefinition();
4170 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4171 }
4172 return TgtBinaryDescriptorQTy;
4173}
4174
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004175namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004176struct PrivateHelpersTy {
4177 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4178 const VarDecl *PrivateElemInit)
4179 : Original(Original), PrivateCopy(PrivateCopy),
4180 PrivateElemInit(PrivateElemInit) {}
4181 const VarDecl *Original;
4182 const VarDecl *PrivateCopy;
4183 const VarDecl *PrivateElemInit;
4184};
4185typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004186} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004187
Alexey Bataev9e034042015-05-05 04:05:12 +00004188static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004189createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004190 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004191 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004192 // Build struct .kmp_privates_t. {
4193 // /* private vars */
4194 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004195 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004196 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004197 for (const auto &Pair : Privates) {
4198 const VarDecl *VD = Pair.second.Original;
4199 QualType Type = VD->getType().getNonReferenceType();
4200 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004201 if (VD->hasAttrs()) {
4202 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4203 E(VD->getAttrs().end());
4204 I != E; ++I)
4205 FD->addAttr(*I);
4206 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004207 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004208 RD->completeDefinition();
4209 return RD;
4210 }
4211 return nullptr;
4212}
4213
Alexey Bataev9e034042015-05-05 04:05:12 +00004214static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004215createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4216 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004217 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004218 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004219 // Build struct kmp_task_t {
4220 // void * shareds;
4221 // kmp_routine_entry_t routine;
4222 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004223 // kmp_cmplrdata_t data1;
4224 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004225 // For taskloops additional fields:
4226 // kmp_uint64 lb;
4227 // kmp_uint64 ub;
4228 // kmp_int64 st;
4229 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004230 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004231 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004232 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004233 UD->startDefinition();
4234 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4235 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4236 UD->completeDefinition();
4237 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004238 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004239 RD->startDefinition();
4240 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4241 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4242 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004243 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4244 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004245 if (isOpenMPTaskLoopDirective(Kind)) {
4246 QualType KmpUInt64Ty =
4247 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4248 QualType KmpInt64Ty =
4249 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4250 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4251 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4252 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4253 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004254 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004255 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004256 RD->completeDefinition();
4257 return RD;
4258}
4259
4260static RecordDecl *
4261createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004262 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004263 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004264 // Build struct kmp_task_t_with_privates {
4265 // kmp_task_t task_data;
4266 // .kmp_privates_t. privates;
4267 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004268 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004269 RD->startDefinition();
4270 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004271 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004272 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004273 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004274 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004275}
4276
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004277/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004278/// argument.
4279/// \code
4280/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004281/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004282/// For taskloops:
4283/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004284/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004285/// return 0;
4286/// }
4287/// \endcode
4288static llvm::Value *
4289emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004290 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4291 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004292 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004293 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4294 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004295 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004296 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004297 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4298 ImplicitParamDecl::Other);
4299 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4300 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4301 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004302 Args.push_back(&GtidArg);
4303 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004304 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004305 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004306 llvm::FunctionType *TaskEntryTy =
4307 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004308 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4309 auto *TaskEntry = llvm::Function::Create(
4310 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004311 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004312 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004313 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004314 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4315 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004316
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004317 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004318 // tt,
4319 // For taskloops:
4320 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4321 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004322 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004323 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004324 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4325 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4326 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004327 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004328 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004329 LValue Base =
4330 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004331 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004332 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004333 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4334 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004335
4336 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004337 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4338 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004339 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004340 CGF.ConvertTypeForMem(SharedsPtrTy));
4341
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004342 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4343 llvm::Value *PrivatesParam;
4344 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004345 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004346 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004347 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004348 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004349 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004350 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004351
Alexey Bataev7292c292016-04-25 12:22:29 +00004352 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4353 TaskPrivatesMap,
4354 CGF.Builder
4355 .CreatePointerBitCastOrAddrSpaceCast(
4356 TDBase.getAddress(), CGF.VoidPtrTy)
4357 .getPointer()};
4358 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4359 std::end(CommonArgs));
4360 if (isOpenMPTaskLoopDirective(Kind)) {
4361 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004362 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4363 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004364 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004365 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4366 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004367 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004368 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4369 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004370 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004371 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4372 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004373 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004374 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4375 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004376 CallArgs.push_back(LBParam);
4377 CallArgs.push_back(UBParam);
4378 CallArgs.push_back(StParam);
4379 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004380 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004381 }
4382 CallArgs.push_back(SharedsParam);
4383
Alexey Bataev3c595a62017-08-14 15:01:03 +00004384 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4385 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004386 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4387 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004388 CGF.FinishFunction();
4389 return TaskEntry;
4390}
4391
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004392static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4393 SourceLocation Loc,
4394 QualType KmpInt32Ty,
4395 QualType KmpTaskTWithPrivatesPtrQTy,
4396 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004397 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004398 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004399 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4400 ImplicitParamDecl::Other);
4401 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4402 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4403 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004404 Args.push_back(&GtidArg);
4405 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004406 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004407 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004408 llvm::FunctionType *DestructorFnTy =
4409 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004410 std::string Name =
4411 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004412 auto *DestructorFn =
4413 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004414 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004415 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004416 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004417 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004418 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004419 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004420 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004421
Alexey Bataev31300ed2016-02-04 11:27:03 +00004422 LValue Base = CGF.EmitLoadOfPointerLValue(
4423 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4424 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004425 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004426 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4427 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004428 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004429 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004430 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004431 if (QualType::DestructionKind DtorKind =
4432 Field->getType().isDestructedType()) {
4433 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004434 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4435 }
4436 }
4437 CGF.FinishFunction();
4438 return DestructorFn;
4439}
4440
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004441/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004442/// firstprivate variables.
4443/// \code
4444/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4445/// **noalias priv1,..., <tyn> **noalias privn) {
4446/// *priv1 = &.privates.priv1;
4447/// ...;
4448/// *privn = &.privates.privn;
4449/// }
4450/// \endcode
4451static llvm::Value *
4452emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004453 ArrayRef<const Expr *> PrivateVars,
4454 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004455 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004456 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004457 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004458 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004459 FunctionArgList Args;
4460 ImplicitParamDecl TaskPrivatesArg(
4461 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004462 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4463 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004464 Args.push_back(&TaskPrivatesArg);
4465 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4466 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004467 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004468 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004469 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4470 C.getPointerType(C.getPointerType(E->getType()))
4471 .withConst()
4472 .withRestrict(),
4473 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004474 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004475 PrivateVarsPos[VD] = Counter;
4476 ++Counter;
4477 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004478 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004479 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004480 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4481 C.getPointerType(C.getPointerType(E->getType()))
4482 .withConst()
4483 .withRestrict(),
4484 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004485 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004486 PrivateVarsPos[VD] = Counter;
4487 ++Counter;
4488 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004489 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004490 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004491 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4492 C.getPointerType(C.getPointerType(E->getType()))
4493 .withConst()
4494 .withRestrict(),
4495 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004496 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004497 PrivateVarsPos[VD] = Counter;
4498 ++Counter;
4499 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004500 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004501 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004502 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004503 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004504 std::string Name =
4505 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004506 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004507 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4508 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004509 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004510 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004511 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004512 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004513 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004514 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004515 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004516 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004517
4518 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004519 LValue Base = CGF.EmitLoadOfPointerLValue(
4520 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4521 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004522 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004523 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004524 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4525 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4526 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4527 LValue RefLVal =
4528 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4529 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004530 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004531 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004532 ++Counter;
4533 }
4534 CGF.FinishFunction();
4535 return TaskPrivatesMap;
4536}
4537
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004538static bool stable_sort_comparator(const PrivateDataTy P1,
4539 const PrivateDataTy P2) {
4540 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004541}
4542
Alexey Bataevf93095a2016-05-05 08:46:22 +00004543/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004544static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004545 const OMPExecutableDirective &D,
4546 Address KmpTaskSharedsPtr, LValue TDBase,
4547 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4548 QualType SharedsTy, QualType SharedsPtrTy,
4549 const OMPTaskDataTy &Data,
4550 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004551 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004552 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4553 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004554 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4555 ? OMPD_taskloop
4556 : OMPD_task;
4557 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4558 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004559 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004560 bool IsTargetTask =
4561 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4562 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4563 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4564 // PointersArray and SizesArray. The original variables for these arrays are
4565 // not captured and we get their addresses explicitly.
4566 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004567 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004568 SrcBase = CGF.MakeAddrLValue(
4569 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4570 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4571 SharedsTy);
4572 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004573 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004574 for (const PrivateDataTy &Pair : Privates) {
4575 const VarDecl *VD = Pair.second.PrivateCopy;
4576 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004577 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4578 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004579 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004580 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4581 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004582 // Check if the variable is the target-based BasePointersArray,
4583 // PointersArray or SizesArray.
4584 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004585 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004586 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004587 if (IsTargetTask && !SharedField) {
4588 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4589 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4590 cast<CapturedDecl>(OriginalVD->getDeclContext())
4591 ->getNumParams() == 0 &&
4592 isa<TranslationUnitDecl>(
4593 cast<CapturedDecl>(OriginalVD->getDeclContext())
4594 ->getDeclContext()) &&
4595 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004596 SharedRefLValue =
4597 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4598 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004599 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4600 SharedRefLValue = CGF.MakeAddrLValue(
4601 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4602 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4603 SharedRefLValue.getTBAAInfo());
4604 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004605 if (Type->isArrayType()) {
4606 // Initialize firstprivate array.
4607 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4608 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004609 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004610 } else {
4611 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004612 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004613 CGF.EmitOMPAggregateAssign(
4614 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4615 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4616 Address SrcElement) {
4617 // Clean up any temporaries needed by the initialization.
4618 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4619 InitScope.addPrivate(
4620 Elem, [SrcElement]() -> Address { return SrcElement; });
4621 (void)InitScope.Privatize();
4622 // Emit initialization for single element.
4623 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4624 CGF, &CapturesInfo);
4625 CGF.EmitAnyExprToMem(Init, DestElement,
4626 Init->getType().getQualifiers(),
4627 /*IsInitializer=*/false);
4628 });
4629 }
4630 } else {
4631 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4632 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4633 return SharedRefLValue.getAddress();
4634 });
4635 (void)InitScope.Privatize();
4636 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4637 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4638 /*capturedByInit=*/false);
4639 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004640 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004641 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004642 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004643 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004644 ++FI;
4645 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004646}
4647
4648/// Check if duplication function is required for taskloops.
4649static bool checkInitIsRequired(CodeGenFunction &CGF,
4650 ArrayRef<PrivateDataTy> Privates) {
4651 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004652 for (const PrivateDataTy &Pair : Privates) {
4653 const VarDecl *VD = Pair.second.PrivateCopy;
4654 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004655 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4656 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004657 if (InitRequired)
4658 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004659 }
4660 return InitRequired;
4661}
4662
4663
4664/// Emit task_dup function (for initialization of
4665/// private/firstprivate/lastprivate vars and last_iter flag)
4666/// \code
4667/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4668/// lastpriv) {
4669/// // setup lastprivate flag
4670/// task_dst->last = lastpriv;
4671/// // could be constructor calls here...
4672/// }
4673/// \endcode
4674static llvm::Value *
4675emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4676 const OMPExecutableDirective &D,
4677 QualType KmpTaskTWithPrivatesPtrQTy,
4678 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4679 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4680 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4681 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004682 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004683 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004684 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4685 KmpTaskTWithPrivatesPtrQTy,
4686 ImplicitParamDecl::Other);
4687 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4688 KmpTaskTWithPrivatesPtrQTy,
4689 ImplicitParamDecl::Other);
4690 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4691 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004692 Args.push_back(&DstArg);
4693 Args.push_back(&SrcArg);
4694 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004695 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004696 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004697 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004698 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4699 auto *TaskDup = llvm::Function::Create(
4700 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004701 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004702 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004703 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004704 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4705 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004706
4707 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4708 CGF.GetAddrOfLocalVar(&DstArg),
4709 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4710 // task_dst->liter = lastpriv;
4711 if (WithLastIter) {
4712 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4713 LValue Base = CGF.EmitLValueForField(
4714 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4715 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4716 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4717 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4718 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4719 }
4720
4721 // Emit initial values for private copies (if any).
4722 assert(!Privates.empty());
4723 Address KmpTaskSharedsPtr = Address::invalid();
4724 if (!Data.FirstprivateVars.empty()) {
4725 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4726 CGF.GetAddrOfLocalVar(&SrcArg),
4727 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4728 LValue Base = CGF.EmitLValueForField(
4729 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4730 KmpTaskSharedsPtr = Address(
4731 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4732 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4733 KmpTaskTShareds)),
4734 Loc),
4735 CGF.getNaturalTypeAlignment(SharedsTy));
4736 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004737 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4738 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004739 CGF.FinishFunction();
4740 return TaskDup;
4741}
4742
Alexey Bataev8a831592016-05-10 10:36:51 +00004743/// Checks if destructor function is required to be generated.
4744/// \return true if cleanups are required, false otherwise.
4745static bool
4746checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4747 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004748 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4749 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4750 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004751 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4752 if (NeedsCleanup)
4753 break;
4754 }
4755 return NeedsCleanup;
4756}
4757
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004758CGOpenMPRuntime::TaskResultTy
4759CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4760 const OMPExecutableDirective &D,
4761 llvm::Value *TaskFunction, QualType SharedsTy,
4762 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004763 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004764 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004765 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004766 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004767 for (const Expr *E : Data.PrivateVars) {
4768 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004769 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004770 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004771 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004772 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004773 ++I;
4774 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004775 I = Data.FirstprivateCopies.begin();
4776 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004777 for (const Expr *E : Data.FirstprivateVars) {
4778 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004779 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004780 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004781 PrivateHelpersTy(
4782 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004783 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004784 ++I;
4785 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004786 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004787 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004788 for (const Expr *E : Data.LastprivateVars) {
4789 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004790 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004791 C.getDeclAlign(VD),
4792 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004793 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004794 ++I;
4795 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004796 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004797 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004798 // Build type kmp_routine_entry_t (if not built yet).
4799 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004800 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004801 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4802 if (SavedKmpTaskloopTQTy.isNull()) {
4803 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4804 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4805 }
4806 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004807 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004808 assert((D.getDirectiveKind() == OMPD_task ||
4809 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4810 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4811 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004812 if (SavedKmpTaskTQTy.isNull()) {
4813 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4814 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4815 }
4816 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004817 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004818 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004819 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004820 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004821 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004822 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004823 QualType KmpTaskTWithPrivatesPtrQTy =
4824 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004825 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4826 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4827 KmpTaskTWithPrivatesTy->getPointerTo();
4828 llvm::Value *KmpTaskTWithPrivatesTySize =
4829 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004830 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4831
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004832 // Emit initial values for private copies (if any).
4833 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004834 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004835 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004836 if (!Privates.empty()) {
4837 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004838 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4839 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4840 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004841 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4842 TaskPrivatesMap, TaskPrivatesMapTy);
4843 } else {
4844 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4845 cast<llvm::PointerType>(TaskPrivatesMapTy));
4846 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004847 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4848 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004849 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004850 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4851 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4852 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004853
4854 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4855 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4856 // kmp_routine_entry_t *task_entry);
4857 // Task flags. Format is taken from
4858 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4859 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004860 enum {
4861 TiedFlag = 0x1,
4862 FinalFlag = 0x2,
4863 DestructorsFlag = 0x8,
4864 PriorityFlag = 0x20
4865 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004866 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004867 bool NeedsCleanup = false;
4868 if (!Privates.empty()) {
4869 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4870 if (NeedsCleanup)
4871 Flags = Flags | DestructorsFlag;
4872 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004873 if (Data.Priority.getInt())
4874 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004875 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004876 Data.Final.getPointer()
4877 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004878 CGF.Builder.getInt32(FinalFlag),
4879 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004880 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004881 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004882 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004883 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4884 getThreadID(CGF, Loc), TaskFlags,
4885 KmpTaskTWithPrivatesTySize, SharedsSize,
4886 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4887 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004888 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004889 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004890 llvm::Value *NewTaskNewTaskTTy =
4891 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4892 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004893 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4894 KmpTaskTWithPrivatesQTy);
4895 LValue TDBase =
4896 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004897 // Fill the data in the resulting kmp_task_t record.
4898 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004899 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004900 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004901 KmpTaskSharedsPtr =
4902 Address(CGF.EmitLoadOfScalar(
4903 CGF.EmitLValueForField(
4904 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4905 KmpTaskTShareds)),
4906 Loc),
4907 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004908 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4909 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004910 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004911 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004912 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004913 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004914 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004915 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4916 SharedsTy, SharedsPtrTy, Data, Privates,
4917 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004918 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4919 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4920 Result.TaskDupFn = emitTaskDupFunction(
4921 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4922 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4923 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004924 }
4925 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004926 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4927 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004928 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004929 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004930 const RecordDecl *KmpCmplrdataUD =
4931 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004932 if (NeedsCleanup) {
4933 llvm::Value *DestructorFn = emitDestructorsFunction(
4934 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4935 KmpTaskTWithPrivatesQTy);
4936 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4937 LValue DestructorsLV = CGF.EmitLValueForField(
4938 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4939 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4940 DestructorFn, KmpRoutineEntryPtrTy),
4941 DestructorsLV);
4942 }
4943 // Set priority.
4944 if (Data.Priority.getInt()) {
4945 LValue Data2LV = CGF.EmitLValueForField(
4946 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4947 LValue PriorityLV = CGF.EmitLValueForField(
4948 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4949 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4950 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004951 Result.NewTask = NewTask;
4952 Result.TaskEntry = TaskEntry;
4953 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4954 Result.TDBase = TDBase;
4955 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4956 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004957}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004958
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004959void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4960 const OMPExecutableDirective &D,
4961 llvm::Value *TaskFunction,
4962 QualType SharedsTy, Address Shareds,
4963 const Expr *IfCond,
4964 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004965 if (!CGF.HaveInsertPoint())
4966 return;
4967
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004968 TaskResultTy Result =
4969 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4970 llvm::Value *NewTask = Result.NewTask;
4971 llvm::Value *TaskEntry = Result.TaskEntry;
4972 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4973 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004974 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4975 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004976 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004977 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004978 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004979 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004980 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004981 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004982 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4983 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004984 QualType FlagsTy =
4985 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004986 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4987 if (KmpDependInfoTy.isNull()) {
4988 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4989 KmpDependInfoRD->startDefinition();
4990 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4991 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4992 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4993 KmpDependInfoRD->completeDefinition();
4994 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004995 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004996 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004997 }
John McCall7f416cc2015-09-08 08:05:57 +00004998 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004999 // Define type kmp_depend_info[<Dependences.size()>];
5000 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005001 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005002 ArrayType::Normal, /*IndexTypeQuals=*/0);
5003 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005004 DependenciesArray =
5005 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005006 for (unsigned I = 0; I < NumDependencies; ++I) {
5007 const Expr *E = Data.Dependences[I].second;
5008 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005009 llvm::Value *Size;
5010 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005011 if (const auto *ASE =
5012 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005013 LValue UpAddrLVal =
5014 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5015 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005016 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005017 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005018 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005019 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5020 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005021 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005022 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005023 }
5024 LValue Base = CGF.MakeAddrLValue(
5025 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005026 KmpDependInfoTy);
5027 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005028 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005029 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005030 CGF.EmitStoreOfScalar(
5031 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5032 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005033 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005034 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005035 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5036 CGF.EmitStoreOfScalar(Size, LenLVal);
5037 // deps[i].flags = <Dependences[i].first>;
5038 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005039 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005040 case OMPC_DEPEND_in:
5041 DepKind = DepIn;
5042 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005043 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005044 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005045 case OMPC_DEPEND_inout:
5046 DepKind = DepInOut;
5047 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005048 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005049 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005050 case OMPC_DEPEND_unknown:
5051 llvm_unreachable("Unknown task dependence type");
5052 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005053 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005054 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5055 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5056 FlagsLVal);
5057 }
John McCall7f416cc2015-09-08 08:05:57 +00005058 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5059 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005060 CGF.VoidPtrTy);
5061 }
5062
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005063 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005064 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005065 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5066 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5067 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5068 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005069 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5070 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005071 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5072 llvm::Value *DepTaskArgs[7];
5073 if (NumDependencies) {
5074 DepTaskArgs[0] = UpLoc;
5075 DepTaskArgs[1] = ThreadID;
5076 DepTaskArgs[2] = NewTask;
5077 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5078 DepTaskArgs[4] = DependenciesArray.getPointer();
5079 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5080 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5081 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005082 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5083 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005084 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005085 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005086 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005087 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005088 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5089 }
John McCall7f416cc2015-09-08 08:05:57 +00005090 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005091 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005092 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005093 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005094 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005095 TaskArgs);
5096 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005097 // Check if parent region is untied and build return for untied task;
5098 if (auto *Region =
5099 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5100 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005101 };
John McCall7f416cc2015-09-08 08:05:57 +00005102
5103 llvm::Value *DepWaitTaskArgs[6];
5104 if (NumDependencies) {
5105 DepWaitTaskArgs[0] = UpLoc;
5106 DepWaitTaskArgs[1] = ThreadID;
5107 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5108 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5109 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5110 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5111 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005112 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005113 NumDependencies, &DepWaitTaskArgs,
5114 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005115 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005116 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5117 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5118 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5119 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5120 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005121 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005122 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005123 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005124 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005125 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5126 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005127 Action.Enter(CGF);
5128 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005129 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005130 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005131 };
5132
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005133 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5134 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005135 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5136 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005137 RegionCodeGenTy RCG(CodeGen);
5138 CommonActionTy Action(
5139 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5140 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5141 RCG.setAction(Action);
5142 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005143 };
John McCall7f416cc2015-09-08 08:05:57 +00005144
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005145 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005146 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005147 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005148 RegionCodeGenTy ThenRCG(ThenCodeGen);
5149 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005150 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005151}
5152
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005153void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5154 const OMPLoopDirective &D,
5155 llvm::Value *TaskFunction,
5156 QualType SharedsTy, Address Shareds,
5157 const Expr *IfCond,
5158 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005159 if (!CGF.HaveInsertPoint())
5160 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005161 TaskResultTy Result =
5162 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005163 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005164 // libcall.
5165 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5166 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5167 // sched, kmp_uint64 grainsize, void *task_dup);
5168 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5169 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5170 llvm::Value *IfVal;
5171 if (IfCond) {
5172 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5173 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005174 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005175 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005176 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005177
5178 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005179 Result.TDBase,
5180 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005181 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005182 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5183 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5184 /*IsInitializer=*/true);
5185 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005186 Result.TDBase,
5187 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005188 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005189 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5190 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5191 /*IsInitializer=*/true);
5192 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005193 Result.TDBase,
5194 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005195 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005196 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5197 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5198 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005199 // Store reductions address.
5200 LValue RedLVal = CGF.EmitLValueForField(
5201 Result.TDBase,
5202 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005203 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005204 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005205 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005206 CGF.EmitNullInitialization(RedLVal.getAddress(),
5207 CGF.getContext().VoidPtrTy);
5208 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005209 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005210 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005211 UpLoc,
5212 ThreadID,
5213 Result.NewTask,
5214 IfVal,
5215 LBLVal.getPointer(),
5216 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005217 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00005218 llvm::ConstantInt::getNullValue(
5219 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005220 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005221 CGF.IntTy, Data.Schedule.getPointer()
5222 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005223 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005224 Data.Schedule.getPointer()
5225 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005226 /*isSigned=*/false)
5227 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005228 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5229 Result.TaskDupFn, CGF.VoidPtrTy)
5230 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005231 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5232}
5233
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005234/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005235/// array sections) LHS op = RHS.
5236/// \param Type Type of array.
5237/// \param LHSVar Variable on the left side of the reduction operation
5238/// (references element of array in original variable).
5239/// \param RHSVar Variable on the right side of the reduction operation
5240/// (references element of array in original variable).
5241/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5242/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005243static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005244 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5245 const VarDecl *RHSVar,
5246 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5247 const Expr *, const Expr *)> &RedOpGen,
5248 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5249 const Expr *UpExpr = nullptr) {
5250 // Perform element-by-element initialization.
5251 QualType ElementTy;
5252 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5253 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5254
5255 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005256 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5257 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005258
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005259 llvm::Value *RHSBegin = RHSAddr.getPointer();
5260 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005261 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005262 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005263 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005264 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5265 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5266 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005267 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5268 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5269
5270 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005271 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005272 CGF.EmitBlock(BodyBB);
5273
5274 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5275
5276 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5277 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5278 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5279 Address RHSElementCurrent =
5280 Address(RHSElementPHI,
5281 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5282
5283 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5284 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5285 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5286 Address LHSElementCurrent =
5287 Address(LHSElementPHI,
5288 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5289
5290 // Emit copy.
5291 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005292 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5293 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005294 Scope.Privatize();
5295 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5296 Scope.ForceCleanup();
5297
5298 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005299 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005300 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005301 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005302 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5303 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005304 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005305 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5306 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5307 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5308 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5309
5310 // Done.
5311 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5312}
5313
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005314/// Emit reduction combiner. If the combiner is a simple expression emit it as
5315/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5316/// UDR combiner function.
5317static void emitReductionCombiner(CodeGenFunction &CGF,
5318 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005319 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5320 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5321 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005322 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005323 if (const auto *DRD =
5324 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005325 std::pair<llvm::Function *, llvm::Function *> Reduction =
5326 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5327 RValue Func = RValue::get(Reduction.first);
5328 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5329 CGF.EmitIgnoredExpr(ReductionOp);
5330 return;
5331 }
5332 CGF.EmitIgnoredExpr(ReductionOp);
5333}
5334
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005335llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005336 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5337 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5338 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005339 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005340
5341 // void reduction_func(void *LHSArg, void *RHSArg);
5342 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005343 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5344 ImplicitParamDecl::Other);
5345 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5346 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005347 Args.push_back(&LHSArg);
5348 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005349 const auto &CGFI =
5350 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005351 std::string Name = getName({"omp", "reduction", "reduction_func"});
5352 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5353 llvm::GlobalValue::InternalLinkage, Name,
5354 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005355 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005356 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005357 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005358 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005359
5360 // Dst = (void*[n])(LHSArg);
5361 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005362 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5363 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5364 ArgsType), CGF.getPointerAlign());
5365 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5366 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5367 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005368
5369 // ...
5370 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5371 // ...
5372 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005373 auto IPriv = Privates.begin();
5374 unsigned Idx = 0;
5375 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005376 const auto *RHSVar =
5377 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5378 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005379 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005380 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005381 const auto *LHSVar =
5382 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5383 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005384 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005385 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005386 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005387 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005388 // Get array size and emit VLA type.
5389 ++Idx;
5390 Address Elem =
5391 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5392 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005393 const VariableArrayType *VLA =
5394 CGF.getContext().getAsVariableArrayType(PrivTy);
5395 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005396 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005397 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005398 CGF.EmitVariablyModifiedType(PrivTy);
5399 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005400 }
5401 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005402 IPriv = Privates.begin();
5403 auto ILHS = LHSExprs.begin();
5404 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005405 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005406 if ((*IPriv)->getType()->isArrayType()) {
5407 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005408 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5409 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005410 EmitOMPAggregateReduction(
5411 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5412 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5413 emitReductionCombiner(CGF, E);
5414 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005415 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005416 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005417 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005418 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005419 ++IPriv;
5420 ++ILHS;
5421 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005422 }
5423 Scope.ForceCleanup();
5424 CGF.FinishFunction();
5425 return Fn;
5426}
5427
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005428void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5429 const Expr *ReductionOp,
5430 const Expr *PrivateRef,
5431 const DeclRefExpr *LHS,
5432 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005433 if (PrivateRef->getType()->isArrayType()) {
5434 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005435 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5436 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005437 EmitOMPAggregateReduction(
5438 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5439 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5440 emitReductionCombiner(CGF, ReductionOp);
5441 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005442 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005443 // Emit reduction for array subscript or single variable.
5444 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005445 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005446}
5447
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005448void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005449 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005450 ArrayRef<const Expr *> LHSExprs,
5451 ArrayRef<const Expr *> RHSExprs,
5452 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005453 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005454 if (!CGF.HaveInsertPoint())
5455 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005456
5457 bool WithNowait = Options.WithNowait;
5458 bool SimpleReduction = Options.SimpleReduction;
5459
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005460 // Next code should be emitted for reduction:
5461 //
5462 // static kmp_critical_name lock = { 0 };
5463 //
5464 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5465 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5466 // ...
5467 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5468 // *(Type<n>-1*)rhs[<n>-1]);
5469 // }
5470 //
5471 // ...
5472 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5473 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5474 // RedList, reduce_func, &<lock>)) {
5475 // case 1:
5476 // ...
5477 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5478 // ...
5479 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5480 // break;
5481 // case 2:
5482 // ...
5483 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5484 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005485 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005486 // break;
5487 // default:;
5488 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005489 //
5490 // if SimpleReduction is true, only the next code is generated:
5491 // ...
5492 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5493 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005494
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005495 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005496
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005497 if (SimpleReduction) {
5498 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005499 auto IPriv = Privates.begin();
5500 auto ILHS = LHSExprs.begin();
5501 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005502 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005503 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5504 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005505 ++IPriv;
5506 ++ILHS;
5507 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005508 }
5509 return;
5510 }
5511
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005512 // 1. Build a list of reduction variables.
5513 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005514 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005515 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005516 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005517 // Reserve place for array size.
5518 ++Size;
5519 }
5520 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005521 QualType ReductionArrayTy =
5522 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5523 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005524 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005525 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005526 auto IPriv = Privates.begin();
5527 unsigned Idx = 0;
5528 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005529 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005530 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005531 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005532 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005533 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5534 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005535 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005536 // Store array size.
5537 ++Idx;
5538 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5539 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005540 llvm::Value *Size = CGF.Builder.CreateIntCast(
5541 CGF.getVLASize(
5542 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005543 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005544 CGF.SizeTy, /*isSigned=*/false);
5545 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5546 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005547 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005548 }
5549
5550 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005551 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005552 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5553 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005554
5555 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005556 std::string Name = getName({"reduction"});
5557 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005558
5559 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5560 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005561 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5562 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5563 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5564 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005565 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005566 llvm::Value *Args[] = {
5567 IdentTLoc, // ident_t *<loc>
5568 ThreadId, // i32 <gtid>
5569 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5570 ReductionArrayTySize, // size_type sizeof(RedList)
5571 RL, // void *RedList
5572 ReductionFn, // void (*) (void *, void *) <reduce_func>
5573 Lock // kmp_critical_name *&<lock>
5574 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005575 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005576 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5577 : OMPRTL__kmpc_reduce),
5578 Args);
5579
5580 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005581 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5582 llvm::SwitchInst *SwInst =
5583 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005584
5585 // 6. Build case 1:
5586 // ...
5587 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5588 // ...
5589 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5590 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005591 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005592 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5593 CGF.EmitBlock(Case1BB);
5594
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005595 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5596 llvm::Value *EndArgs[] = {
5597 IdentTLoc, // ident_t *<loc>
5598 ThreadId, // i32 <gtid>
5599 Lock // kmp_critical_name *&<lock>
5600 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005601 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5602 CodeGenFunction &CGF, PrePostActionTy &Action) {
5603 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005604 auto IPriv = Privates.begin();
5605 auto ILHS = LHSExprs.begin();
5606 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005607 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005608 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5609 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005610 ++IPriv;
5611 ++ILHS;
5612 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005613 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005614 };
5615 RegionCodeGenTy RCG(CodeGen);
5616 CommonActionTy Action(
5617 nullptr, llvm::None,
5618 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5619 : OMPRTL__kmpc_end_reduce),
5620 EndArgs);
5621 RCG.setAction(Action);
5622 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005623
5624 CGF.EmitBranch(DefaultBB);
5625
5626 // 7. Build case 2:
5627 // ...
5628 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5629 // ...
5630 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005631 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005632 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5633 CGF.EmitBlock(Case2BB);
5634
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005635 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5636 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005637 auto ILHS = LHSExprs.begin();
5638 auto IRHS = RHSExprs.begin();
5639 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005640 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005641 const Expr *XExpr = nullptr;
5642 const Expr *EExpr = nullptr;
5643 const Expr *UpExpr = nullptr;
5644 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005645 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005646 if (BO->getOpcode() == BO_Assign) {
5647 XExpr = BO->getLHS();
5648 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005649 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005650 }
5651 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005652 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005653 if (RHSExpr) {
5654 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005655 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005656 RHSExpr->IgnoreParenImpCasts())) {
5657 // If this is a conditional operator, analyze its condition for
5658 // min/max reduction operator.
5659 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005660 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005661 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005662 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5663 EExpr = BORHS->getRHS();
5664 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005665 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005666 }
5667 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005668 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005669 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005670 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5671 const Expr *EExpr, const Expr *UpExpr) {
5672 LValue X = CGF.EmitLValue(XExpr);
5673 RValue E;
5674 if (EExpr)
5675 E = CGF.EmitAnyExpr(EExpr);
5676 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005677 X, E, BO, /*IsXLHSInRHSPart=*/true,
5678 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005679 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005680 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5681 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005682 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005683 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5684 CGF.emitOMPSimpleStore(
5685 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5686 VD->getType().getNonReferenceType(), Loc);
5687 return LHSTemp;
5688 });
5689 (void)PrivateScope.Privatize();
5690 return CGF.EmitAnyExpr(UpExpr);
5691 });
5692 };
5693 if ((*IPriv)->getType()->isArrayType()) {
5694 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005695 const auto *RHSVar =
5696 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005697 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5698 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005699 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005700 // Emit atomic reduction for array subscript or single variable.
5701 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005702 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005703 } else {
5704 // Emit as a critical region.
5705 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005706 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005707 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005708 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005709 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005710 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005711 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5712 Action.Enter(CGF);
5713 emitReductionCombiner(CGF, E);
5714 },
5715 Loc);
5716 };
5717 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005718 const auto *LHSVar =
5719 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5720 const auto *RHSVar =
5721 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005722 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5723 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005724 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005725 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005726 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005727 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005728 ++ILHS;
5729 ++IRHS;
5730 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005731 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005732 };
5733 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5734 if (!WithNowait) {
5735 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5736 llvm::Value *EndArgs[] = {
5737 IdentTLoc, // ident_t *<loc>
5738 ThreadId, // i32 <gtid>
5739 Lock // kmp_critical_name *&<lock>
5740 };
5741 CommonActionTy Action(nullptr, llvm::None,
5742 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5743 EndArgs);
5744 AtomicRCG.setAction(Action);
5745 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005746 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005747 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005748 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005749
5750 CGF.EmitBranch(DefaultBB);
5751 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5752}
5753
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005754/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005755/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5756static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5757 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005758 SmallString<256> Buffer;
5759 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005760 const clang::DeclRefExpr *DE;
5761 const VarDecl *D = ::getBaseDecl(Ref, DE);
5762 if (!D)
5763 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5764 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005765 std::string Name = CGM.getOpenMPRuntime().getName(
5766 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5767 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005768 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005769 return Out.str();
5770}
5771
5772/// Emits reduction initializer function:
5773/// \code
5774/// void @.red_init(void* %arg) {
5775/// %0 = bitcast void* %arg to <type>*
5776/// store <type> <init>, <type>* %0
5777/// ret void
5778/// }
5779/// \endcode
5780static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5781 SourceLocation Loc,
5782 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005783 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005784 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005785 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5786 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005787 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005788 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005789 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005790 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005791 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005792 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005793 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005794 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005795 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005796 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005797 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005798 Address PrivateAddr = CGF.EmitLoadOfPointer(
5799 CGF.GetAddrOfLocalVar(&Param),
5800 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5801 llvm::Value *Size = nullptr;
5802 // If the size of the reduction item is non-constant, load it from global
5803 // threadprivate variable.
5804 if (RCG.getSizes(N).second) {
5805 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5806 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005807 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005808 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5809 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005810 }
5811 RCG.emitAggregateType(CGF, N, Size);
5812 LValue SharedLVal;
5813 // If initializer uses initializer from declare reduction construct, emit a
5814 // pointer to the address of the original reduction item (reuired by reduction
5815 // initializer)
5816 if (RCG.usesReductionInitializer(N)) {
5817 Address SharedAddr =
5818 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5819 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005820 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005821 SharedAddr = CGF.EmitLoadOfPointer(
5822 SharedAddr,
5823 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005824 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5825 } else {
5826 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5827 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5828 CGM.getContext().VoidPtrTy);
5829 }
5830 // Emit the initializer:
5831 // %0 = bitcast void* %arg to <type>*
5832 // store <type> <init>, <type>* %0
5833 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5834 [](CodeGenFunction &) { return false; });
5835 CGF.FinishFunction();
5836 return Fn;
5837}
5838
5839/// Emits reduction combiner function:
5840/// \code
5841/// void @.red_comb(void* %arg0, void* %arg1) {
5842/// %lhs = bitcast void* %arg0 to <type>*
5843/// %rhs = bitcast void* %arg1 to <type>*
5844/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5845/// store <type> %2, <type>* %lhs
5846/// ret void
5847/// }
5848/// \endcode
5849static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5850 SourceLocation Loc,
5851 ReductionCodeGen &RCG, unsigned N,
5852 const Expr *ReductionOp,
5853 const Expr *LHS, const Expr *RHS,
5854 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005855 ASTContext &C = CGM.getContext();
5856 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5857 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005858 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005859 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5860 C.VoidPtrTy, ImplicitParamDecl::Other);
5861 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5862 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005863 Args.emplace_back(&ParamInOut);
5864 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005865 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005866 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005867 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005868 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005869 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005870 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005871 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005872 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005873 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005874 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005875 llvm::Value *Size = nullptr;
5876 // If the size of the reduction item is non-constant, load it from global
5877 // threadprivate variable.
5878 if (RCG.getSizes(N).second) {
5879 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5880 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005881 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005882 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5883 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005884 }
5885 RCG.emitAggregateType(CGF, N, Size);
5886 // Remap lhs and rhs variables to the addresses of the function arguments.
5887 // %lhs = bitcast void* %arg0 to <type>*
5888 // %rhs = bitcast void* %arg1 to <type>*
5889 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005890 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005891 // Pull out the pointer to the variable.
5892 Address PtrAddr = CGF.EmitLoadOfPointer(
5893 CGF.GetAddrOfLocalVar(&ParamInOut),
5894 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5895 return CGF.Builder.CreateElementBitCast(
5896 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5897 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005898 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005899 // Pull out the pointer to the variable.
5900 Address PtrAddr = CGF.EmitLoadOfPointer(
5901 CGF.GetAddrOfLocalVar(&ParamIn),
5902 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5903 return CGF.Builder.CreateElementBitCast(
5904 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5905 });
5906 PrivateScope.Privatize();
5907 // Emit the combiner body:
5908 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5909 // store <type> %2, <type>* %lhs
5910 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5911 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5912 cast<DeclRefExpr>(RHS));
5913 CGF.FinishFunction();
5914 return Fn;
5915}
5916
5917/// Emits reduction finalizer function:
5918/// \code
5919/// void @.red_fini(void* %arg) {
5920/// %0 = bitcast void* %arg to <type>*
5921/// <destroy>(<type>* %0)
5922/// ret void
5923/// }
5924/// \endcode
5925static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5926 SourceLocation Loc,
5927 ReductionCodeGen &RCG, unsigned N) {
5928 if (!RCG.needCleanups(N))
5929 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005930 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005931 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005932 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5933 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005934 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005935 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005936 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005937 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005938 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005939 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005940 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005941 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005942 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005943 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005944 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005945 Address PrivateAddr = CGF.EmitLoadOfPointer(
5946 CGF.GetAddrOfLocalVar(&Param),
5947 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5948 llvm::Value *Size = nullptr;
5949 // If the size of the reduction item is non-constant, load it from global
5950 // threadprivate variable.
5951 if (RCG.getSizes(N).second) {
5952 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5953 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005954 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005955 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5956 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005957 }
5958 RCG.emitAggregateType(CGF, N, Size);
5959 // Emit the finalizer body:
5960 // <destroy>(<type>* %0)
5961 RCG.emitCleanups(CGF, N, PrivateAddr);
5962 CGF.FinishFunction();
5963 return Fn;
5964}
5965
5966llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5967 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5968 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5969 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5970 return nullptr;
5971
5972 // Build typedef struct:
5973 // kmp_task_red_input {
5974 // void *reduce_shar; // shared reduction item
5975 // size_t reduce_size; // size of data item
5976 // void *reduce_init; // data initialization routine
5977 // void *reduce_fini; // data finalization routine
5978 // void *reduce_comb; // data combiner routine
5979 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5980 // } kmp_task_red_input_t;
5981 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005982 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005983 RD->startDefinition();
5984 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5985 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5986 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5987 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5988 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5989 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5990 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5991 RD->completeDefinition();
5992 QualType RDType = C.getRecordType(RD);
5993 unsigned Size = Data.ReductionVars.size();
5994 llvm::APInt ArraySize(/*numBits=*/64, Size);
5995 QualType ArrayRDType = C.getConstantArrayType(
5996 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5997 // kmp_task_red_input_t .rd_input.[Size];
5998 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5999 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6000 Data.ReductionOps);
6001 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6002 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6003 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6004 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6005 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6006 TaskRedInput.getPointer(), Idxs,
6007 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6008 ".rd_input.gep.");
6009 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6010 // ElemLVal.reduce_shar = &Shareds[Cnt];
6011 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6012 RCG.emitSharedLValue(CGF, Cnt);
6013 llvm::Value *CastedShared =
6014 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6015 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6016 RCG.emitAggregateType(CGF, Cnt);
6017 llvm::Value *SizeValInChars;
6018 llvm::Value *SizeVal;
6019 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6020 // We use delayed creation/initialization for VLAs, array sections and
6021 // custom reduction initializations. It is required because runtime does not
6022 // provide the way to pass the sizes of VLAs/array sections to
6023 // initializer/combiner/finalizer functions and does not pass the pointer to
6024 // original reduction item to the initializer. Instead threadprivate global
6025 // variables are used to store these values and use them in the functions.
6026 bool DelayedCreation = !!SizeVal;
6027 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6028 /*isSigned=*/false);
6029 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6030 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6031 // ElemLVal.reduce_init = init;
6032 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6033 llvm::Value *InitAddr =
6034 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6035 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6036 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6037 // ElemLVal.reduce_fini = fini;
6038 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6039 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6040 llvm::Value *FiniAddr = Fini
6041 ? CGF.EmitCastToVoidPtr(Fini)
6042 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6043 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6044 // ElemLVal.reduce_comb = comb;
6045 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6046 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6047 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6048 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6049 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6050 // ElemLVal.flags = 0;
6051 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6052 if (DelayedCreation) {
6053 CGF.EmitStoreOfScalar(
6054 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6055 FlagsLVal);
6056 } else
6057 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6058 }
6059 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6060 // *data);
6061 llvm::Value *Args[] = {
6062 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6063 /*isSigned=*/true),
6064 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6065 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6066 CGM.VoidPtrTy)};
6067 return CGF.EmitRuntimeCall(
6068 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6069}
6070
6071void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6072 SourceLocation Loc,
6073 ReductionCodeGen &RCG,
6074 unsigned N) {
6075 auto Sizes = RCG.getSizes(N);
6076 // Emit threadprivate global variable if the type is non-constant
6077 // (Sizes.second = nullptr).
6078 if (Sizes.second) {
6079 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6080 /*isSigned=*/false);
6081 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6082 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006083 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006084 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6085 }
6086 // Store address of the original reduction item if custom initializer is used.
6087 if (RCG.usesReductionInitializer(N)) {
6088 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6089 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006090 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006091 CGF.Builder.CreateStore(
6092 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6093 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6094 SharedAddr, /*IsVolatile=*/false);
6095 }
6096}
6097
6098Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6099 SourceLocation Loc,
6100 llvm::Value *ReductionsPtr,
6101 LValue SharedLVal) {
6102 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6103 // *d);
6104 llvm::Value *Args[] = {
6105 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6106 /*isSigned=*/true),
6107 ReductionsPtr,
6108 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6109 CGM.VoidPtrTy)};
6110 return Address(
6111 CGF.EmitRuntimeCall(
6112 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6113 SharedLVal.getAlignment());
6114}
6115
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006116void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6117 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006118 if (!CGF.HaveInsertPoint())
6119 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006120 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6121 // global_tid);
6122 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6123 // Ignore return result until untied tasks are supported.
6124 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006125 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6126 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006127}
6128
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006129void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006130 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006131 const RegionCodeGenTy &CodeGen,
6132 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006133 if (!CGF.HaveInsertPoint())
6134 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006135 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006136 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006137}
6138
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006139namespace {
6140enum RTCancelKind {
6141 CancelNoreq = 0,
6142 CancelParallel = 1,
6143 CancelLoop = 2,
6144 CancelSections = 3,
6145 CancelTaskgroup = 4
6146};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006147} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006148
6149static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6150 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006151 if (CancelRegion == OMPD_parallel)
6152 CancelKind = CancelParallel;
6153 else if (CancelRegion == OMPD_for)
6154 CancelKind = CancelLoop;
6155 else if (CancelRegion == OMPD_sections)
6156 CancelKind = CancelSections;
6157 else {
6158 assert(CancelRegion == OMPD_taskgroup);
6159 CancelKind = CancelTaskgroup;
6160 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006161 return CancelKind;
6162}
6163
6164void CGOpenMPRuntime::emitCancellationPointCall(
6165 CodeGenFunction &CGF, SourceLocation Loc,
6166 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006167 if (!CGF.HaveInsertPoint())
6168 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006169 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6170 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006171 if (auto *OMPRegionInfo =
6172 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006173 // For 'cancellation point taskgroup', the task region info may not have a
6174 // cancel. This may instead happen in another adjacent task.
6175 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006176 llvm::Value *Args[] = {
6177 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6178 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006179 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006180 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006181 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6182 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006183 // exit from construct;
6184 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006185 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6186 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6187 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006188 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6189 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006190 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006191 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006192 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006193 CGF.EmitBranchThroughCleanup(CancelDest);
6194 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6195 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006196 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006197}
6198
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006199void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006200 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006201 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006202 if (!CGF.HaveInsertPoint())
6203 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006204 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6205 // kmp_int32 cncl_kind);
6206 if (auto *OMPRegionInfo =
6207 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006208 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6209 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006210 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006211 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006212 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006213 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6214 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006215 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006216 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006217 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006218 // exit from construct;
6219 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006220 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6221 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6222 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006223 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6224 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006225 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006226 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006227 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6228 CGF.EmitBranchThroughCleanup(CancelDest);
6229 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6230 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006231 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006232 emitOMPIfClause(CGF, IfCond, ThenGen,
6233 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006234 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006235 RegionCodeGenTy ThenRCG(ThenGen);
6236 ThenRCG(CGF);
6237 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006238 }
6239}
Samuel Antaobed3c462015-10-02 16:14:20 +00006240
Samuel Antaoee8fb302016-01-06 13:42:12 +00006241void CGOpenMPRuntime::emitTargetOutlinedFunction(
6242 const OMPExecutableDirective &D, StringRef ParentName,
6243 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006244 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006245 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006246 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6247 IsOffloadEntry, CodeGen);
6248}
6249
6250void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6251 const OMPExecutableDirective &D, StringRef ParentName,
6252 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6253 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006254 // Create a unique name for the entry function using the source location
6255 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006256 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006257 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006258 //
6259 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006260 // mangled name of the function that encloses the target region and BB is the
6261 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006262
6263 unsigned DeviceID;
6264 unsigned FileID;
6265 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006266 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006267 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006268 SmallString<64> EntryFnName;
6269 {
6270 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006271 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6272 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006273 }
6274
Alexey Bataev475a7442018-01-12 19:39:11 +00006275 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006276
Samuel Antaobed3c462015-10-02 16:14:20 +00006277 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006278 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006279 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006280
Samuel Antao6d004262016-06-16 18:39:34 +00006281 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006282
6283 // If this target outline function is not an offload entry, we don't need to
6284 // register it.
6285 if (!IsOffloadEntry)
6286 return;
6287
6288 // The target region ID is used by the runtime library to identify the current
6289 // target region, so it only has to be unique and not necessarily point to
6290 // anything. It could be the pointer to the outlined function that implements
6291 // the target region, but we aren't using that so that the compiler doesn't
6292 // need to keep that, and could therefore inline the host function if proven
6293 // worthwhile during optimization. In the other hand, if emitting code for the
6294 // device, the ID has to be the function address so that it can retrieved from
6295 // the offloading entry and launched by the runtime library. We also mark the
6296 // outlined function to have external linkage in case we are emitting code for
6297 // the device, because these functions will be entry points to the device.
6298
6299 if (CGM.getLangOpts().OpenMPIsDevice) {
6300 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006301 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006302 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006303 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006304 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006305 OutlinedFnID = new llvm::GlobalVariable(
6306 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006307 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006308 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006309 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006310
6311 // Register the information for the entry associated with this target region.
6312 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006313 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006314 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006315}
6316
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006317/// discard all CompoundStmts intervening between two constructs
6318static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006319 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006320 Body = CS->body_front();
6321
6322 return Body;
6323}
6324
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006325/// Emit the number of teams for a target directive. Inspect the num_teams
6326/// clause associated with a teams construct combined or closely nested
6327/// with the target directive.
6328///
6329/// Emit a team of size one for directives such as 'target parallel' that
6330/// have no associated teams construct.
6331///
6332/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006333static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006334emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6335 CodeGenFunction &CGF,
6336 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006337 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6338 "teams directive expected to be "
6339 "emitted only for the host!");
6340
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006341 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006342
6343 // If the target directive is combined with a teams directive:
6344 // Return the value in the num_teams clause, if any.
6345 // Otherwise, return 0 to denote the runtime default.
6346 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6347 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6348 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006349 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6350 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006351 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6352 /*IsSigned=*/true);
6353 }
6354
6355 // The default value is 0.
6356 return Bld.getInt32(0);
6357 }
6358
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006359 // If the target directive is combined with a parallel directive but not a
6360 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006361 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6362 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006363
6364 // If the current target region has a teams region enclosed, we need to get
6365 // the number of teams to pass to the runtime function call. This is done
6366 // by generating the expression in a inlined region. This is required because
6367 // the expression is captured in the enclosing target environment when the
6368 // teams directive is not combined with target.
6369
Alexey Bataev475a7442018-01-12 19:39:11 +00006370 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006371
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006372 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006373 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006374 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006375 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006376 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6377 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6378 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6379 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6380 /*IsSigned=*/true);
6381 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006382
Alexey Bataev50a1c782017-12-01 21:31:08 +00006383 // If we have an enclosed teams directive but no num_teams clause we use
6384 // the default value 0.
6385 return Bld.getInt32(0);
6386 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006387 }
6388
6389 // No teams associated with the directive.
6390 return nullptr;
6391}
6392
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006393/// Emit the number of threads for a target directive. Inspect the
6394/// thread_limit clause associated with a teams construct combined or closely
6395/// nested with the target directive.
6396///
6397/// Emit the num_threads clause for directives such as 'target parallel' that
6398/// have no associated teams construct.
6399///
6400/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006401static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006402emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6403 CodeGenFunction &CGF,
6404 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006405 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6406 "teams directive expected to be "
6407 "emitted only for the host!");
6408
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006409 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006410
6411 //
6412 // If the target directive is combined with a teams directive:
6413 // Return the value in the thread_limit clause, if any.
6414 //
6415 // If the target directive is combined with a parallel directive:
6416 // Return the value in the num_threads clause, if any.
6417 //
6418 // If both clauses are set, select the minimum of the two.
6419 //
6420 // If neither teams or parallel combined directives set the number of threads
6421 // in a team, return 0 to denote the runtime default.
6422 //
6423 // If this is not a teams directive return nullptr.
6424
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006425 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6426 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006427 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6428 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006429 llvm::Value *ThreadLimitVal = nullptr;
6430
6431 if (const auto *ThreadLimitClause =
6432 D.getSingleClause<OMPThreadLimitClause>()) {
6433 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006434 llvm::Value *ThreadLimit =
6435 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6436 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006437 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6438 /*IsSigned=*/true);
6439 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006440
6441 if (const auto *NumThreadsClause =
6442 D.getSingleClause<OMPNumThreadsClause>()) {
6443 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6444 llvm::Value *NumThreads =
6445 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6446 /*IgnoreResultAssign*/ true);
6447 NumThreadsVal =
6448 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6449 }
6450
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006451 // Select the lesser of thread_limit and num_threads.
6452 if (NumThreadsVal)
6453 ThreadLimitVal = ThreadLimitVal
6454 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6455 ThreadLimitVal),
6456 NumThreadsVal, ThreadLimitVal)
6457 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006458
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006459 // Set default value passed to the runtime if either teams or a target
6460 // parallel type directive is found but no clause is specified.
6461 if (!ThreadLimitVal)
6462 ThreadLimitVal = DefaultThreadLimitVal;
6463
6464 return ThreadLimitVal;
6465 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006466
Samuel Antaob68e2db2016-03-03 16:20:23 +00006467 // If the current target region has a teams region enclosed, we need to get
6468 // the thread limit to pass to the runtime function call. This is done
6469 // by generating the expression in a inlined region. This is required because
6470 // the expression is captured in the enclosing target environment when the
6471 // teams directive is not combined with target.
6472
Alexey Bataev475a7442018-01-12 19:39:11 +00006473 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006474
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006475 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006476 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006477 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006478 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006479 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6480 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6481 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6482 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6483 /*IsSigned=*/true);
6484 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006485
Alexey Bataev50a1c782017-12-01 21:31:08 +00006486 // If we have an enclosed teams directive but no thread_limit clause we
6487 // use the default value 0.
6488 return CGF.Builder.getInt32(0);
6489 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006490 }
6491
6492 // No teams associated with the directive.
6493 return nullptr;
6494}
6495
Samuel Antao86ace552016-04-27 22:40:57 +00006496namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006497LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6498
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006499// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006500// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6501// It provides a convenient interface to obtain the information and generate
6502// code for that information.
6503class MappableExprsHandler {
6504public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006505 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006506 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006507 enum OpenMPOffloadMappingFlags : uint64_t {
6508 /// No flags
6509 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006510 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006511 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006512 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006513 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006514 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006515 /// if it was already mapped before.
6516 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006517 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006518 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006519 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006520 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006521 /// pointer and the pointee should be mapped.
6522 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006523 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006524 /// passed to the target kernel as an argument.
6525 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006526 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006527 /// in the current position for the data being mapped. Used when we have the
6528 /// use_device_ptr clause.
6529 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006530 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006531 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006532 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006533 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006534 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006535 /// Implicit map
6536 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006537 /// The 16 MSBs of the flags indicate whether the entry is member of some
6538 /// struct/class.
6539 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6540 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006541 };
6542
Samuel Antaocc10b852016-07-28 14:23:26 +00006543 /// Class that associates information with a base pointer to be passed to the
6544 /// runtime library.
6545 class BasePointerInfo {
6546 /// The base pointer.
6547 llvm::Value *Ptr = nullptr;
6548 /// The base declaration that refers to this device pointer, or null if
6549 /// there is none.
6550 const ValueDecl *DevPtrDecl = nullptr;
6551
6552 public:
6553 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6554 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6555 llvm::Value *operator*() const { return Ptr; }
6556 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6557 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6558 };
6559
Alexey Bataevb3638132018-07-19 16:34:13 +00006560 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6561 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6562 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6563
6564 /// Map between a struct and the its lowest & highest elements which have been
6565 /// mapped.
6566 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6567 /// HE(FieldIndex, Pointer)}
6568 struct StructRangeInfoTy {
6569 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6570 0, Address::invalid()};
6571 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6572 0, Address::invalid()};
6573 Address Base = Address::invalid();
6574 };
Samuel Antao86ace552016-04-27 22:40:57 +00006575
6576private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006577 /// Kind that defines how a device pointer has to be returned.
6578 struct MapInfo {
6579 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6580 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6581 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6582 bool ReturnDevicePointer = false;
6583 bool IsImplicit = false;
6584
6585 MapInfo() = default;
6586 MapInfo(
6587 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6588 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6589 bool ReturnDevicePointer, bool IsImplicit)
6590 : Components(Components), MapType(MapType),
6591 MapTypeModifier(MapTypeModifier),
6592 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6593 };
6594
6595 /// If use_device_ptr is used on a pointer which is a struct member and there
6596 /// is no map information about it, then emission of that entry is deferred
6597 /// until the whole struct has been processed.
6598 struct DeferredDevicePtrEntryTy {
6599 const Expr *IE = nullptr;
6600 const ValueDecl *VD = nullptr;
6601
6602 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6603 : IE(IE), VD(VD) {}
6604 };
6605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006606 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006607 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006609 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006610 CodeGenFunction &CGF;
6611
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006612 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006613 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6614
Samuel Antao6890b092016-07-28 14:25:09 +00006615 /// Map between device pointer declarations and their expression components.
6616 /// The key value for declarations in 'this' is null.
6617 llvm::DenseMap<
6618 const ValueDecl *,
6619 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6620 DevPointersMap;
6621
Samuel Antao86ace552016-04-27 22:40:57 +00006622 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006623 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006624
6625 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006626 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006627 ExprTy = RefTy->getPointeeType().getCanonicalType();
6628
6629 // Given that an array section is considered a built-in type, we need to
6630 // do the calculation based on the length of the section instead of relying
6631 // on CGF.getTypeSize(E->getType()).
6632 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6633 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6634 OAE->getBase()->IgnoreParenImpCasts())
6635 .getCanonicalType();
6636
6637 // If there is no length associated with the expression, that means we
6638 // are using the whole length of the base.
6639 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6640 return CGF.getTypeSize(BaseTy);
6641
6642 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006643 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006644 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006645 } else {
6646 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006647 assert(ATy && "Expecting array type if not a pointer type.");
6648 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6649 }
6650
6651 // If we don't have a length at this point, that is because we have an
6652 // array section with a single element.
6653 if (!OAE->getLength())
6654 return ElemSize;
6655
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006656 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006657 LengthVal =
6658 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6659 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6660 }
6661 return CGF.getTypeSize(ExprTy);
6662 }
6663
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006664 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006665 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006666 /// map as the first one of a series of maps that relate to the same map
6667 /// expression.
Alexey Bataevb3638132018-07-19 16:34:13 +00006668 OpenMPOffloadMappingFlags getMapTypeBits(OpenMPMapClauseKind MapType,
6669 OpenMPMapClauseKind MapTypeModifier,
6670 bool IsImplicit, bool AddPtrFlag,
6671 bool AddIsTargetParamFlag) const {
6672 OpenMPOffloadMappingFlags Bits =
6673 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006674 switch (MapType) {
6675 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006676 case OMPC_MAP_release:
6677 // alloc and release is the default behavior in the runtime library, i.e.
6678 // if we don't pass any bits alloc/release that is what the runtime is
6679 // going to do. Therefore, we don't need to signal anything for these two
6680 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006681 break;
6682 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006683 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006684 break;
6685 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006686 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006687 break;
6688 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006689 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006690 break;
6691 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006692 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006693 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006694 case OMPC_MAP_always:
6695 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006696 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006697 }
6698 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006699 Bits |= OMP_MAP_PTR_AND_OBJ;
6700 if (AddIsTargetParamFlag)
6701 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006702 if (MapTypeModifier == OMPC_MAP_always)
6703 Bits |= OMP_MAP_ALWAYS;
6704 return Bits;
6705 }
6706
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006707 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006708 /// final array section, is one whose length can't be proved to be one.
6709 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006710 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006711
6712 // It is not an array section and therefore not a unity-size one.
6713 if (!OASE)
6714 return false;
6715
6716 // An array section with no colon always refer to a single element.
6717 if (OASE->getColonLoc().isInvalid())
6718 return false;
6719
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006720 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006721
6722 // If we don't have a length we have to check if the array has size 1
6723 // for this dimension. Also, we should always expect a length if the
6724 // base type is pointer.
6725 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006726 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6727 OASE->getBase()->IgnoreParenImpCasts())
6728 .getCanonicalType();
6729 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006730 return ATy->getSize().getSExtValue() != 1;
6731 // If we don't have a constant dimension length, we have to consider
6732 // the current section as having any size, so it is not necessarily
6733 // unitary. If it happen to be unity size, that's user fault.
6734 return true;
6735 }
6736
6737 // Check if the length evaluates to 1.
6738 llvm::APSInt ConstLength;
6739 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6740 return true; // Can have more that size 1.
6741
6742 return ConstLength.getSExtValue() != 1;
6743 }
6744
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006745 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006746 /// bits for the provided map type, map modifier, and expression components.
6747 /// \a IsFirstComponent should be set to true if the provided set of
6748 /// components is the first associated with a capture.
6749 void generateInfoForComponentList(
6750 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6751 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006752 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006753 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006754 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006755 bool IsImplicit,
6756 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6757 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006758 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006759 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006760 // base pointer, section pointer, size, flags
6761 // (to add to the ones that come from the map type and modifier).
6762 //
6763 // double d;
6764 // int i[100];
6765 // float *p;
6766 //
6767 // struct S1 {
6768 // int i;
6769 // float f[50];
6770 // }
6771 // struct S2 {
6772 // int i;
6773 // float f[50];
6774 // S1 s;
6775 // double *p;
6776 // struct S2 *ps;
6777 // }
6778 // S2 s;
6779 // S2 *ps;
6780 //
6781 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006782 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006783 //
6784 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006785 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006786 //
6787 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006788 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006789 //
6790 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006791 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006792 //
6793 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006794 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006795 //
6796 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006797 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006798 //
6799 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006800 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006801 //
6802 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006803 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006804 //
6805 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006806 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006807 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006808 // map(to: s.p[:22])
6809 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6810 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6811 // &(s.p), &(s.p[0]), 22*sizeof(double),
6812 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6813 // (*) alloc space for struct members, only this is a target parameter
6814 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6815 // optimizes this entry out, same in the examples below)
6816 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006817 //
6818 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006819 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006820 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006821 // map(from: s.ps->s.i)
6822 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6823 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6824 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006825 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006826 // map(to: s.ps->ps)
6827 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6828 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6829 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006830 //
6831 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006832 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6833 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6834 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6835 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006836 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006837 // map(to: s.ps->ps->s.f[:22])
6838 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6839 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6840 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6841 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006842 //
6843 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006844 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006845 //
6846 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006847 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006848 //
6849 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006850 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006851 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006852 // map(from: ps->p)
6853 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006854 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006855 // map(to: ps->p[:22])
6856 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6857 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6858 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006859 //
6860 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006861 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006862 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006863 // map(from: ps->ps->s.i)
6864 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6865 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6866 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006867 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006868 // map(from: ps->ps->ps)
6869 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6870 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6871 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006872 //
6873 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006874 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6875 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6876 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6877 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006878 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006879 // map(to: ps->ps->ps->s.f[:22])
6880 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6881 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6882 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6883 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6884 //
6885 // map(to: s.f[:22]) map(from: s.p[:33])
6886 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
6887 // sizeof(double*) (**), TARGET_PARAM
6888 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
6889 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
6890 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
6891 // (*) allocate contiguous space needed to fit all mapped members even if
6892 // we allocate space for members not mapped (in this example,
6893 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
6894 // them as well because they fall between &s.f[0] and &s.p)
6895 //
6896 // map(from: s.f[:22]) map(to: ps->p[:33])
6897 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
6898 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6899 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
6900 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
6901 // (*) the struct this entry pertains to is the 2nd element in the list of
6902 // arguments, hence MEMBER_OF(2)
6903 //
6904 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
6905 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
6906 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
6907 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
6908 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6909 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
6910 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
6911 // (*) the struct this entry pertains to is the 4th element in the list
6912 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00006913
6914 // Track if the map information being generated is the first for a capture.
6915 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006916 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006917
6918 // Scan the components from the base to the complete expression.
6919 auto CI = Components.rbegin();
6920 auto CE = Components.rend();
6921 auto I = CI;
6922
6923 // Track if the map information being generated is the first for a list of
6924 // components.
6925 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006926 Address BP = Address::invalid();
Samuel Antao86ace552016-04-27 22:40:57 +00006927
Erich Keanee69755a2018-07-19 17:19:16 +00006928 if (isa<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006929 // The base is the 'this' pointer. The content of the pointer is going
6930 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00006931 BP = CGF.LoadCXXThisAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00006932 } else {
6933 // The base is the reference to the variable.
6934 // BP = &Var.
Alexey Bataevb3638132018-07-19 16:34:13 +00006935 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00006936 if (const auto *VD =
6937 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6938 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00006939 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006940 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
6941 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006942 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006943 }
Alexey Bataev92327c52018-03-26 16:40:55 +00006944 }
Samuel Antao86ace552016-04-27 22:40:57 +00006945
6946 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006947 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006948 // reference. References are ignored for mapping purposes.
6949 QualType Ty =
6950 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6951 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00006952 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00006953
6954 // We do not need to generate individual map information for the
6955 // pointer, it can be associated with the combined storage.
6956 ++I;
6957 }
6958 }
6959
Alexey Bataevb3638132018-07-19 16:34:13 +00006960 // Track whether a component of the list should be marked as MEMBER_OF some
6961 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
6962 // in a component list should be marked as MEMBER_OF, all subsequent entries
6963 // do not belong to the base struct. E.g.
6964 // struct S2 s;
6965 // s.ps->ps->ps->f[:]
6966 // (1) (2) (3) (4)
6967 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
6968 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
6969 // is the pointee of ps(2) which is not member of struct s, so it should not
6970 // be marked as such (it is still PTR_AND_OBJ).
6971 // The variable is initialized to false so that PTR_AND_OBJ entries which
6972 // are not struct members are not considered (e.g. array of pointers to
6973 // data).
6974 bool ShouldBeMemberOf = false;
6975
6976 // Variable keeping track of whether or not we have encountered a component
6977 // in the component list which is a member expression. Useful when we have a
6978 // pointer or a final array section, in which case it is the previous
6979 // component in the list which tells us whether we have a member expression.
6980 // E.g. X.f[:]
6981 // While processing the final array section "[:]" it is "f" which tells us
6982 // whether we are dealing with a member of a declared struct.
6983 const MemberExpr *EncounteredME = nullptr;
6984
Samuel Antao86ace552016-04-27 22:40:57 +00006985 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00006986 // If the current component is member of a struct (parent struct) mark it.
6987 if (!EncounteredME) {
6988 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
6989 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
6990 // as MEMBER_OF the parent struct.
6991 if (EncounteredME)
6992 ShouldBeMemberOf = true;
6993 }
6994
Samuel Antao86ace552016-04-27 22:40:57 +00006995 auto Next = std::next(I);
6996
6997 // We need to generate the addresses and sizes if this is the last
6998 // component, if the component is a pointer or if it is an array section
6999 // whose length can't be proved to be one. If this is a pointer, it
7000 // becomes the base address for the following components.
7001
7002 // A final array section, is one whose length can't be proved to be one.
7003 bool IsFinalArraySection =
7004 isFinalArraySectionExpression(I->getAssociatedExpression());
7005
7006 // Get information on whether the element is a pointer. Have to do a
7007 // special treatment for array sections given that they are built-in
7008 // types.
7009 const auto *OASE =
7010 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7011 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007012 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7013 .getCanonicalType()
7014 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007015 I->getAssociatedExpression()->getType()->isAnyPointerType();
7016
7017 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007018 // If this is not the last component, we expect the pointer to be
7019 // associated with an array expression or member expression.
7020 assert((Next == CE ||
7021 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7022 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7023 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7024 "Unexpected expression");
7025
Alexey Bataevb3638132018-07-19 16:34:13 +00007026 Address LB =
7027 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007028
Alexey Bataevb3638132018-07-19 16:34:13 +00007029 // If this component is a pointer inside the base struct then we don't
7030 // need to create any entry for it - it will be combined with the object
7031 // it is pointing to into a single PTR_AND_OBJ entry.
7032 bool IsMemberPointer =
7033 IsPointer && EncounteredME &&
7034 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7035 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007036 if (!OverlappedElements.empty()) {
7037 // Handle base element with the info for overlapped elements.
7038 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7039 assert(Next == CE &&
7040 "Expected last element for the overlapped elements.");
7041 assert(!IsPointer &&
7042 "Unexpected base element with the pointer type.");
7043 // Mark the whole struct as the struct that requires allocation on the
7044 // device.
7045 PartialStruct.LowestElem = {0, LB};
7046 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7047 I->getAssociatedExpression()->getType());
7048 Address HB = CGF.Builder.CreateConstGEP(
7049 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7050 CGF.VoidPtrTy),
7051 TypeSize.getQuantity() - 1, CharUnits::One());
7052 PartialStruct.HighestElem = {
7053 std::numeric_limits<decltype(
7054 PartialStruct.HighestElem.first)>::max(),
7055 HB};
7056 PartialStruct.Base = BP;
7057 // Emit data for non-overlapped data.
7058 OpenMPOffloadMappingFlags Flags =
7059 OMP_MAP_MEMBER_OF |
7060 getMapTypeBits(MapType, MapTypeModifier, IsImplicit,
7061 /*AddPtrFlag=*/false,
7062 /*AddIsTargetParamFlag=*/false);
7063 LB = BP;
7064 llvm::Value *Size = nullptr;
7065 // Do bitcopy of all non-overlapped structure elements.
7066 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7067 Component : OverlappedElements) {
7068 Address ComponentLB = Address::invalid();
7069 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7070 Component) {
7071 if (MC.getAssociatedDeclaration()) {
7072 ComponentLB =
7073 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7074 .getAddress();
7075 Size = CGF.Builder.CreatePtrDiff(
7076 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7077 CGF.EmitCastToVoidPtr(LB.getPointer()));
7078 break;
7079 }
7080 }
7081 BasePointers.push_back(BP.getPointer());
7082 Pointers.push_back(LB.getPointer());
7083 Sizes.push_back(Size);
7084 Types.push_back(Flags);
7085 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1,
7086 CGF.getPointerSize());
7087 }
7088 BasePointers.push_back(BP.getPointer());
7089 Pointers.push_back(LB.getPointer());
7090 Size = CGF.Builder.CreatePtrDiff(
7091 CGF.EmitCastToVoidPtr(
7092 CGF.Builder.CreateConstGEP(HB, 1, CharUnits::One())
7093 .getPointer()),
7094 CGF.EmitCastToVoidPtr(LB.getPointer()));
7095 Sizes.push_back(Size);
7096 Types.push_back(Flags);
7097 break;
7098 }
7099 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007100 if (!IsMemberPointer) {
7101 BasePointers.push_back(BP.getPointer());
7102 Pointers.push_back(LB.getPointer());
7103 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007104
Alexey Bataevb3638132018-07-19 16:34:13 +00007105 // We need to add a pointer flag for each map that comes from the
7106 // same expression except for the first one. We also need to signal
7107 // this map is the first one that relates with the current capture
7108 // (there is a set of entries for each capture).
7109 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
7110 MapType, MapTypeModifier, IsImplicit,
7111 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7112
7113 if (!IsExpressionFirstInfo) {
7114 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7115 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7116 if (IsPointer)
7117 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7118 OMP_MAP_DELETE);
7119
7120 if (ShouldBeMemberOf) {
7121 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7122 // should be later updated with the correct value of MEMBER_OF.
7123 Flags |= OMP_MAP_MEMBER_OF;
7124 // From now on, all subsequent PTR_AND_OBJ entries should not be
7125 // marked as MEMBER_OF.
7126 ShouldBeMemberOf = false;
7127 }
7128 }
7129
7130 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007131 }
7132
Alexey Bataevb3638132018-07-19 16:34:13 +00007133 // If we have encountered a member expression so far, keep track of the
7134 // mapped member. If the parent is "*this", then the value declaration
7135 // is nullptr.
7136 if (EncounteredME) {
7137 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7138 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007139
Alexey Bataevb3638132018-07-19 16:34:13 +00007140 // Update info about the lowest and highest elements for this struct
7141 if (!PartialStruct.Base.isValid()) {
7142 PartialStruct.LowestElem = {FieldIndex, LB};
7143 PartialStruct.HighestElem = {FieldIndex, LB};
7144 PartialStruct.Base = BP;
7145 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7146 PartialStruct.LowestElem = {FieldIndex, LB};
7147 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7148 PartialStruct.HighestElem = {FieldIndex, LB};
7149 }
7150 }
Samuel Antao86ace552016-04-27 22:40:57 +00007151
7152 // If we have a final array section, we are done with this expression.
7153 if (IsFinalArraySection)
7154 break;
7155
7156 // The pointer becomes the base for the next element.
7157 if (Next != CE)
7158 BP = LB;
7159
7160 IsExpressionFirstInfo = false;
7161 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007162 }
7163 }
7164 }
7165
Alexey Bataevb3638132018-07-19 16:34:13 +00007166 /// Return the adjusted map modifiers if the declaration a capture refers to
7167 /// appears in a first-private clause. This is expected to be used only with
7168 /// directives that start with 'target'.
7169 MappableExprsHandler::OpenMPOffloadMappingFlags
7170 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7171 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7172
7173 // A first private variable captured by reference will use only the
7174 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7175 // declaration is known as first-private in this handler.
7176 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
7177 return MappableExprsHandler::OMP_MAP_PRIVATE |
7178 MappableExprsHandler::OMP_MAP_TO;
7179 return MappableExprsHandler::OMP_MAP_TO |
7180 MappableExprsHandler::OMP_MAP_FROM;
7181 }
7182
7183 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7184 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7185 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7186 << 48);
7187 }
7188
7189 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7190 OpenMPOffloadMappingFlags MemberOfFlag) {
7191 // If the entry is PTR_AND_OBJ but has not been marked with the special
7192 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7193 // marked as MEMBER_OF.
7194 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7195 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7196 return;
7197
7198 // Reset the placeholder value to prepare the flag for the assignment of the
7199 // proper MEMBER_OF value.
7200 Flags &= ~OMP_MAP_MEMBER_OF;
7201 Flags |= MemberOfFlag;
7202 }
7203
Alexey Bataeve82445f2018-09-20 13:54:02 +00007204 void getPlainLayout(const CXXRecordDecl *RD,
7205 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7206 bool AsBase) const {
7207 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7208
7209 llvm::StructType *St =
7210 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7211
7212 unsigned NumElements = St->getNumElements();
7213 llvm::SmallVector<
7214 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7215 RecordLayout(NumElements);
7216
7217 // Fill bases.
7218 for (const auto &I : RD->bases()) {
7219 if (I.isVirtual())
7220 continue;
7221 const auto *Base = I.getType()->getAsCXXRecordDecl();
7222 // Ignore empty bases.
7223 if (Base->isEmpty() || CGF.getContext()
7224 .getASTRecordLayout(Base)
7225 .getNonVirtualSize()
7226 .isZero())
7227 continue;
7228
7229 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7230 RecordLayout[FieldIndex] = Base;
7231 }
7232 // Fill in virtual bases.
7233 for (const auto &I : RD->vbases()) {
7234 const auto *Base = I.getType()->getAsCXXRecordDecl();
7235 // Ignore empty bases.
7236 if (Base->isEmpty())
7237 continue;
7238 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7239 if (RecordLayout[FieldIndex])
7240 continue;
7241 RecordLayout[FieldIndex] = Base;
7242 }
7243 // Fill in all the fields.
7244 assert(!RD->isUnion() && "Unexpected union.");
7245 for (const auto *Field : RD->fields()) {
7246 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7247 // will fill in later.)
7248 if (!Field->isBitField()) {
7249 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7250 RecordLayout[FieldIndex] = Field;
7251 }
7252 }
7253 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7254 &Data : RecordLayout) {
7255 if (Data.isNull())
7256 continue;
7257 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7258 getPlainLayout(Base, Layout, /*AsBase=*/true);
7259 else
7260 Layout.push_back(Data.get<const FieldDecl *>());
7261 }
7262 }
7263
Alexey Bataevb3638132018-07-19 16:34:13 +00007264public:
7265 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7266 : CurDir(Dir), CGF(CGF) {
7267 // Extract firstprivate clause information.
7268 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7269 for (const auto *D : C->varlists())
7270 FirstPrivateDecls.insert(
7271 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7272 // Extract device pointer clause information.
7273 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7274 for (auto L : C->component_lists())
7275 DevPointersMap[L.first].push_back(L.second);
7276 }
7277
7278 /// Generate code for the combined entry if we have a partially mapped struct
7279 /// and take care of the mapping flags of the arguments corresponding to
7280 /// individual struct members.
7281 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7282 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7283 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7284 const StructRangeInfoTy &PartialStruct) const {
7285 // Base is the base of the struct
7286 BasePointers.push_back(PartialStruct.Base.getPointer());
7287 // Pointer is the address of the lowest element
7288 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7289 Pointers.push_back(LB);
7290 // Size is (addr of {highest+1} element) - (addr of lowest element)
7291 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7292 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7293 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7294 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7295 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7296 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7297 /*isSinged=*/false);
7298 Sizes.push_back(Size);
7299 // Map type is always TARGET_PARAM
7300 Types.push_back(OMP_MAP_TARGET_PARAM);
7301 // Remove TARGET_PARAM flag from the first element
7302 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7303
7304 // All other current entries will be MEMBER_OF the combined entry
7305 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7306 // 0xFFFF in the MEMBER_OF field).
7307 OpenMPOffloadMappingFlags MemberOfFlag =
7308 getMemberOfFlag(BasePointers.size() - 1);
7309 for (auto &M : CurTypes)
7310 setCorrectMemberOfFlag(M, MemberOfFlag);
7311 }
7312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007313 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007314 /// types for the extracted mappable expressions. Also, for each item that
7315 /// relates with a device pointer, a pair of the relevant declaration and
7316 /// index where it occurs is appended to the device pointers info array.
7317 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007318 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7319 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007320 // We have to process the component lists that relate with the same
7321 // declaration in a single chunk so that we can generate the map flags
7322 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007323 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007324
7325 // Helper function to fill the information map for the different supported
7326 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007327 auto &&InfoGen = [&Info](
7328 const ValueDecl *D,
7329 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7330 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevb3638132018-07-19 16:34:13 +00007331 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007332 const ValueDecl *VD =
7333 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007334 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7335 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007336 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007337
Paul Robinson78fb1322016-08-01 22:12:46 +00007338 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007339 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7340 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007341 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007342 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007343 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007344 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7345 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007346 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007347 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007348 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007349 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7350 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007351 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007352 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007353 }
Samuel Antao86ace552016-04-27 22:40:57 +00007354
Samuel Antaocc10b852016-07-28 14:23:26 +00007355 // Look at the use_device_ptr clause information and mark the existing map
7356 // entries as such. If there is no map information for an entry in the
7357 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007358 // section. It is the user fault if that was not mapped before. If there is
7359 // no map information and the pointer is a struct member, then we defer the
7360 // emission of that entry until the whole struct has been processed.
7361 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7362 DeferredInfo;
7363
Paul Robinson78fb1322016-08-01 22:12:46 +00007364 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007365 for (const auto *C :
7366 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007367 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007368 assert(!L.second.empty() && "Not expecting empty list of components!");
7369 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7370 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007371 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007372 // If the first component is a member expression, we have to look into
7373 // 'this', which maps to null in the map of map information. Otherwise
7374 // look directly for the information.
7375 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7376
7377 // We potentially have map information for this declaration already.
7378 // Look for the first set of components that refer to it.
7379 if (It != Info.end()) {
7380 auto CI = std::find_if(
7381 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7382 return MI.Components.back().getAssociatedDeclaration() == VD;
7383 });
7384 // If we found a map entry, signal that the pointer has to be returned
7385 // and move on to the next declaration.
7386 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007387 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007388 continue;
7389 }
7390 }
7391
7392 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007393 // size array section - if the pointer is a struct member we defer this
7394 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007395 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007396 if (isa<MemberExpr>(IE)) {
7397 // Insert the pointer into Info to be processed by
7398 // generateInfoForComponentList. Because it is a member pointer
7399 // without a pointee, no entry will be generated for it, therefore
7400 // we need to generate one after the whole struct has been processed.
7401 // Nonetheless, generateInfoForComponentList must be called to take
7402 // the pointer into account for the calculation of the range of the
7403 // partial struct.
7404 InfoGen(nullptr, L.second, OMPC_MAP_unknown, OMPC_MAP_unknown,
7405 /*ReturnDevicePointer=*/false, C->isImplicit());
7406 DeferredInfo[nullptr].emplace_back(IE, VD);
7407 } else {
7408 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7409 this->CGF.EmitLValue(IE), IE->getExprLoc());
7410 BasePointers.emplace_back(Ptr, VD);
7411 Pointers.push_back(Ptr);
7412 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7413 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7414 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007415 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007416 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007417
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007418 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007419 // We need to know when we generate information for the first component
7420 // associated with a capture, because the mapping flags depend on it.
7421 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007422
7423 // Temporary versions of arrays
7424 MapBaseValuesArrayTy CurBasePointers;
7425 MapValuesArrayTy CurPointers;
7426 MapValuesArrayTy CurSizes;
7427 MapFlagsArrayTy CurTypes;
7428 StructRangeInfoTy PartialStruct;
7429
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007430 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007431 assert(!L.Components.empty() &&
7432 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007433
7434 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007435 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007436 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007437 this->generateInfoForComponentList(
Alexey Bataevb3638132018-07-19 16:34:13 +00007438 L.MapType, L.MapTypeModifier, L.Components, CurBasePointers,
7439 CurPointers, CurSizes, CurTypes, PartialStruct,
7440 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007441
7442 // If this entry relates with a device pointer, set the relevant
7443 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007444 if (L.ReturnDevicePointer) {
7445 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007446 "Unexpected number of mapped base pointers.");
7447
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007448 const ValueDecl *RelevantVD =
7449 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007450 assert(RelevantVD &&
7451 "No relevant declaration related with device pointer??");
7452
Alexey Bataevb3638132018-07-19 16:34:13 +00007453 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7454 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007455 }
Samuel Antao86ace552016-04-27 22:40:57 +00007456 IsFirstComponentList = false;
7457 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007458
7459 // Append any pending zero-length pointers which are struct members and
7460 // used with use_device_ptr.
7461 auto CI = DeferredInfo.find(M.first);
7462 if (CI != DeferredInfo.end()) {
7463 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7464 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7465 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7466 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7467 CurBasePointers.emplace_back(BasePtr, L.VD);
7468 CurPointers.push_back(Ptr);
7469 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7470 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7471 // value MEMBER_OF=FFFF so that the entry is later updated with the
7472 // correct value of MEMBER_OF.
7473 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7474 OMP_MAP_MEMBER_OF);
7475 }
7476 }
7477
7478 // If there is an entry in PartialStruct it means we have a struct with
7479 // individual members mapped. Emit an extra combined entry.
7480 if (PartialStruct.Base.isValid())
7481 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7482 PartialStruct);
7483
7484 // We need to append the results of this capture to what we already have.
7485 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7486 Pointers.append(CurPointers.begin(), CurPointers.end());
7487 Sizes.append(CurSizes.begin(), CurSizes.end());
7488 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007489 }
7490 }
7491
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007492 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007493 /// associated to a given capture.
7494 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007495 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007496 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007497 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007498 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7499 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007500 assert(!Cap->capturesVariableArrayType() &&
7501 "Not expecting to generate map info for a variable array type!");
7502
Samuel Antao6890b092016-07-28 14:25:09 +00007503 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007504 const ValueDecl *VD = Cap->capturesThis()
7505 ? nullptr
7506 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007507
Samuel Antao6890b092016-07-28 14:25:09 +00007508 // If this declaration appears in a is_device_ptr clause we just have to
7509 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007510 // pass its value.
7511 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007512 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007513 Pointers.push_back(Arg);
7514 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007515 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007516 return;
7517 }
7518
Alexey Bataeve82445f2018-09-20 13:54:02 +00007519 using MapData =
7520 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
7521 OpenMPMapClauseKind, OpenMPMapClauseKind, bool>;
7522 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007523 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007524 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007525 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007526 assert(L.first == VD &&
7527 "We got information for the wrong declaration??");
7528 assert(!L.second.empty() &&
7529 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007530 DeclComponentLists.emplace_back(L.second, C->getMapType(),
7531 C->getMapTypeModifier(),
7532 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007533 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007534 }
7535
7536 // Find overlapping elements (including the offset from the base element).
7537 llvm::SmallDenseMap<
7538 const MapData *,
7539 llvm::SmallVector<
7540 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7541 4>
7542 OverlappedData;
7543 size_t Count = 0;
7544 for (const MapData &L : DeclComponentLists) {
7545 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7546 OpenMPMapClauseKind MapType;
7547 OpenMPMapClauseKind MapTypeModifier;
7548 bool IsImplicit;
7549 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7550 ++Count;
7551 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7552 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
7553 std::tie(Components1, MapType, MapTypeModifier, IsImplicit) = L1;
7554 auto CI = Components.rbegin();
7555 auto CE = Components.rend();
7556 auto SI = Components1.rbegin();
7557 auto SE = Components1.rend();
7558 for (; CI != CE && SI != SE; ++CI, ++SI) {
7559 if (CI->getAssociatedExpression()->getStmtClass() !=
7560 SI->getAssociatedExpression()->getStmtClass())
7561 break;
7562 // Are we dealing with different variables/fields?
7563 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7564 break;
7565 }
7566 // Found overlapping if, at least for one component, reached the head of
7567 // the components list.
7568 if (CI == CE || SI == SE) {
7569 assert((CI != CE || SI != SE) &&
7570 "Unexpected full match of the mapping components.");
7571 const MapData &BaseData = CI == CE ? L : L1;
7572 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7573 SI == SE ? Components : Components1;
7574 auto It = CI == CE ? SI : CI;
7575 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7576 OverlappedElements.getSecond().push_back(SubData);
7577 }
7578 }
7579 }
7580 // Sort the overlapped elements for each item.
7581 llvm::SmallVector<const FieldDecl *, 4> Layout;
7582 if (!OverlappedData.empty()) {
7583 if (const auto *CRD =
7584 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7585 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7586 else {
7587 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7588 Layout.append(RD->field_begin(), RD->field_end());
7589 }
7590 }
7591 for (auto &Pair : OverlappedData) {
7592 llvm::sort(
7593 Pair.getSecond(),
7594 [&Layout](
7595 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7596 OMPClauseMappableExprCommon::MappableExprComponentListRef
7597 Second) {
7598 auto CI = First.rbegin();
7599 auto CE = First.rend();
7600 auto SI = Second.rbegin();
7601 auto SE = Second.rend();
7602 for (; CI != CE && SI != SE; ++CI, ++SI) {
7603 if (CI->getAssociatedExpression()->getStmtClass() !=
7604 SI->getAssociatedExpression()->getStmtClass())
7605 break;
7606 // Are we dealing with different variables/fields?
7607 if (CI->getAssociatedDeclaration() !=
7608 SI->getAssociatedDeclaration())
7609 break;
7610 }
7611 assert(CI != CE && SI != SE &&
7612 "Unexpected end of the map components.");
7613 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7614 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7615 if (FD1->getParent() == FD2->getParent())
7616 return FD1->getFieldIndex() < FD2->getFieldIndex();
7617 const auto It =
7618 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7619 return FD == FD1 || FD == FD2;
7620 });
7621 return *It == FD1;
7622 });
7623 }
7624
7625 // Associated with a capture, because the mapping flags depend on it.
7626 // Go through all of the elements with the overlapped elements.
7627 for (const auto &Pair : OverlappedData) {
7628 const MapData &L = *Pair.getFirst();
7629 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7630 OpenMPMapClauseKind MapType;
7631 OpenMPMapClauseKind MapTypeModifier;
7632 bool IsImplicit;
7633 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7634 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7635 OverlappedComponents = Pair.getSecond();
7636 bool IsFirstComponentList = true;
7637 generateInfoForComponentList(MapType, MapTypeModifier, Components,
7638 BasePointers, Pointers, Sizes, Types,
7639 PartialStruct, IsFirstComponentList,
7640 IsImplicit, OverlappedComponents);
7641 }
7642 // Go through other elements without overlapped elements.
7643 bool IsFirstComponentList = OverlappedData.empty();
7644 for (const MapData &L : DeclComponentLists) {
7645 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7646 OpenMPMapClauseKind MapType;
7647 OpenMPMapClauseKind MapTypeModifier;
7648 bool IsImplicit;
7649 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7650 auto It = OverlappedData.find(&L);
7651 if (It == OverlappedData.end())
7652 generateInfoForComponentList(MapType, MapTypeModifier, Components,
7653 BasePointers, Pointers, Sizes, Types,
7654 PartialStruct, IsFirstComponentList,
7655 IsImplicit);
7656 IsFirstComponentList = false;
7657 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007658 }
Samuel Antao86ace552016-04-27 22:40:57 +00007659
Alexey Bataevb3638132018-07-19 16:34:13 +00007660 /// Generate the base pointers, section pointers, sizes and map types
7661 /// associated with the declare target link variables.
7662 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7663 MapValuesArrayTy &Pointers,
7664 MapValuesArrayTy &Sizes,
7665 MapFlagsArrayTy &Types) const {
7666 // Map other list items in the map clause which are not captured variables
7667 // but "declare target link" global variables.,
7668 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7669 for (const auto &L : C->component_lists()) {
7670 if (!L.first)
7671 continue;
7672 const auto *VD = dyn_cast<VarDecl>(L.first);
7673 if (!VD)
7674 continue;
7675 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007676 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007677 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7678 continue;
7679 StructRangeInfoTy PartialStruct;
7680 generateInfoForComponentList(
7681 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7682 Pointers, Sizes, Types, PartialStruct,
7683 /*IsFirstComponentList=*/true, C->isImplicit());
7684 assert(!PartialStruct.Base.isValid() &&
7685 "No partial structs for declare target link expected.");
7686 }
7687 }
Samuel Antao86ace552016-04-27 22:40:57 +00007688 }
Samuel Antaod486f842016-05-26 16:53:38 +00007689
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007690 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007691 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007692 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7693 const FieldDecl &RI, llvm::Value *CV,
7694 MapBaseValuesArrayTy &CurBasePointers,
7695 MapValuesArrayTy &CurPointers,
7696 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007697 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007698 // Do the default mapping.
7699 if (CI.capturesThis()) {
7700 CurBasePointers.push_back(CV);
7701 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007702 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007703 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7704 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007705 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007706 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007707 CurBasePointers.push_back(CV);
7708 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007709 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007710 // We have to signal to the runtime captures passed by value that are
7711 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007712 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007713 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7714 } else {
7715 // Pointers are implicitly mapped with a zero size and no flags
7716 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007717 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007718 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7719 }
7720 } else {
7721 assert(CI.capturesVariable() && "Expected captured reference.");
7722 CurBasePointers.push_back(CV);
7723 CurPointers.push_back(CV);
7724
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007725 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007726 QualType ElementType = PtrTy->getPointeeType();
7727 CurSizes.push_back(CGF.getTypeSize(ElementType));
7728 // The default map type for a scalar/complex type is 'to' because by
7729 // default the value doesn't have to be retrieved. For an aggregate
7730 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007731 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Samuel Antaod486f842016-05-26 16:53:38 +00007732 }
George Rokos065755d2017-11-07 18:27:04 +00007733 // Every default map produces a single argument which is a target parameter.
7734 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007735
7736 // Add flag stating this is an implicit map.
7737 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007738 }
Samuel Antao86ace552016-04-27 22:40:57 +00007739};
Samuel Antaodf158d52016-04-27 22:58:19 +00007740
7741enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007742 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007743 /// from environment variables in the spec.
7744 OMP_DEVICEID_UNDEF = -1,
7745};
7746} // anonymous namespace
7747
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007748/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007749/// offloading runtime library. If there is no map or capture information,
7750/// return nullptr by reference.
7751static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007752emitOffloadingArrays(CodeGenFunction &CGF,
7753 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007754 MappableExprsHandler::MapValuesArrayTy &Pointers,
7755 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007756 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7757 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007758 CodeGenModule &CGM = CGF.CGM;
7759 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007760
Samuel Antaocc10b852016-07-28 14:23:26 +00007761 // Reset the array information.
7762 Info.clearArrayInfo();
7763 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007764
Samuel Antaocc10b852016-07-28 14:23:26 +00007765 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007766 // Detect if we have any capture size requiring runtime evaluation of the
7767 // size so that a constant array could be eventually used.
7768 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007769 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007770 if (!isa<llvm::Constant>(S)) {
7771 hasRuntimeEvaluationCaptureSize = true;
7772 break;
7773 }
7774
Samuel Antaocc10b852016-07-28 14:23:26 +00007775 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007776 QualType PointerArrayType =
7777 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7778 /*IndexTypeQuals=*/0);
7779
Samuel Antaocc10b852016-07-28 14:23:26 +00007780 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007781 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007782 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007783 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7784
7785 // If we don't have any VLA types or other types that require runtime
7786 // evaluation, we can use a constant array for the map sizes, otherwise we
7787 // need to fill up the arrays as we do for the pointers.
7788 if (hasRuntimeEvaluationCaptureSize) {
7789 QualType SizeArrayType = Ctx.getConstantArrayType(
7790 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7791 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007792 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007793 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7794 } else {
7795 // We expect all the sizes to be constant, so we collect them to create
7796 // a constant array.
7797 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007798 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007799 ConstSizes.push_back(cast<llvm::Constant>(S));
7800
7801 auto *SizesArrayInit = llvm::ConstantArray::get(
7802 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007803 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007804 auto *SizesArrayGbl = new llvm::GlobalVariable(
7805 CGM.getModule(), SizesArrayInit->getType(),
7806 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007807 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007808 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007809 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007810 }
7811
7812 // The map types are always constant so we don't need to generate code to
7813 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00007814 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
7815 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00007816 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00007817 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007818 std::string MaptypesName =
7819 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007820 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7821 CGM.getModule(), MapTypesArrayInit->getType(),
7822 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007823 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007824 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007825 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007826
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007827 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7828 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007829 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007830 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007831 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007832 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7833 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007834 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7835 CGF.Builder.CreateStore(BPVal, BPAddr);
7836
Samuel Antaocc10b852016-07-28 14:23:26 +00007837 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007838 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007839 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007840
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007841 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007842 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007843 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007844 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007845 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7846 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007847 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7848 CGF.Builder.CreateStore(PVal, PAddr);
7849
7850 if (hasRuntimeEvaluationCaptureSize) {
7851 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007852 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7853 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007854 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007855 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00007856 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7857 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007858 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00007859 SAddr);
7860 }
7861 }
7862 }
7863}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007864/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00007865/// arrays of pointers, sizes and map types.
7866static void emitOffloadingArraysArgument(
7867 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7868 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007869 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007870 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007871 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007872 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007873 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7874 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007875 /*Idx0=*/0, /*Idx1=*/0);
7876 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007877 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7878 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007879 /*Idx0=*/0,
7880 /*Idx1=*/0);
7881 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007882 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007883 /*Idx0=*/0, /*Idx1=*/0);
7884 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007885 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007886 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007887 /*Idx0=*/0,
7888 /*Idx1=*/0);
7889 } else {
7890 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7891 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7892 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7893 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007894 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007895 }
Samuel Antao86ace552016-04-27 22:40:57 +00007896}
7897
Samuel Antaobed3c462015-10-02 16:14:20 +00007898void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7899 const OMPExecutableDirective &D,
7900 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007901 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007902 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007903 if (!CGF.HaveInsertPoint())
7904 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007905
Samuel Antaoee8fb302016-01-06 13:42:12 +00007906 assert(OutlinedFn && "Invalid outlined function!");
7907
Alexey Bataev8451efa2018-01-15 19:06:12 +00007908 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7909 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007910 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007911 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7912 PrePostActionTy &) {
7913 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7914 };
7915 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007916
Alexey Bataev8451efa2018-01-15 19:06:12 +00007917 CodeGenFunction::OMPTargetDataInfo InputInfo;
7918 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007919 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007920 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7921 &MapTypesArray, &CS, RequiresOuterTask,
7922 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007923 // On top of the arrays that were filled up, the target offloading call
7924 // takes as arguments the device id as well as the host pointer. The host
7925 // pointer is used by the runtime library to identify the current target
7926 // region, so it only has to be unique and not necessarily point to
7927 // anything. It could be the pointer to the outlined function that
7928 // implements the target region, but we aren't using that so that the
7929 // compiler doesn't need to keep that, and could therefore inline the host
7930 // function if proven worthwhile during optimization.
7931
Samuel Antaoee8fb302016-01-06 13:42:12 +00007932 // From this point on, we need to have an ID of the target region defined.
7933 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007934
7935 // Emit device ID if any.
7936 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007937 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007938 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007939 CGF.Int64Ty, /*isSigned=*/true);
7940 } else {
7941 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7942 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007943
Samuel Antaodf158d52016-04-27 22:58:19 +00007944 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007945 llvm::Value *PointerNum =
7946 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007947
Samuel Antaob68e2db2016-03-03 16:20:23 +00007948 // Return value of the runtime offloading call.
7949 llvm::Value *Return;
7950
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007951 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7952 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007953
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007954 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007955 // The target region is an outlined function launched by the runtime
7956 // via calls __tgt_target() or __tgt_target_teams().
7957 //
7958 // __tgt_target() launches a target region with one team and one thread,
7959 // executing a serial region. This master thread may in turn launch
7960 // more threads within its team upon encountering a parallel region,
7961 // however, no additional teams can be launched on the device.
7962 //
7963 // __tgt_target_teams() launches a target region with one or more teams,
7964 // each with one or more threads. This call is required for target
7965 // constructs such as:
7966 // 'target teams'
7967 // 'target' / 'teams'
7968 // 'target teams distribute parallel for'
7969 // 'target parallel'
7970 // and so on.
7971 //
7972 // Note that on the host and CPU targets, the runtime implementation of
7973 // these calls simply call the outlined function without forking threads.
7974 // The outlined functions themselves have runtime calls to
7975 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7976 // the compiler in emitTeamsCall() and emitParallelCall().
7977 //
7978 // In contrast, on the NVPTX target, the implementation of
7979 // __tgt_target_teams() launches a GPU kernel with the requested number
7980 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007981 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007982 // If we have NumTeams defined this means that we have an enclosed teams
7983 // region. Therefore we also expect to have NumThreads defined. These two
7984 // values should be defined in the presence of a teams directive,
7985 // regardless of having any clauses associated. If the user is using teams
7986 // but no clauses, these two values will be the default that should be
7987 // passed to the runtime library - a 32-bit integer with the value zero.
7988 assert(NumThreads && "Thread limit expression should be available along "
7989 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007990 llvm::Value *OffloadingArgs[] = {DeviceID,
7991 OutlinedFnID,
7992 PointerNum,
7993 InputInfo.BasePointersArray.getPointer(),
7994 InputInfo.PointersArray.getPointer(),
7995 InputInfo.SizesArray.getPointer(),
7996 MapTypesArray,
7997 NumTeams,
7998 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007999 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008000 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8001 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008002 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008003 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008004 llvm::Value *OffloadingArgs[] = {DeviceID,
8005 OutlinedFnID,
8006 PointerNum,
8007 InputInfo.BasePointersArray.getPointer(),
8008 InputInfo.PointersArray.getPointer(),
8009 InputInfo.SizesArray.getPointer(),
8010 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008011 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008012 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8013 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008014 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008015 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008016
Alexey Bataev2a007e02017-10-02 14:20:58 +00008017 // Check the error code and execute the host version if required.
8018 llvm::BasicBlock *OffloadFailedBlock =
8019 CGF.createBasicBlock("omp_offload.failed");
8020 llvm::BasicBlock *OffloadContBlock =
8021 CGF.createBasicBlock("omp_offload.cont");
8022 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8023 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8024
8025 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008026 if (RequiresOuterTask) {
8027 CapturedVars.clear();
8028 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8029 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008030 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008031 CGF.EmitBranch(OffloadContBlock);
8032
8033 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008034 };
8035
Samuel Antaoee8fb302016-01-06 13:42:12 +00008036 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008037 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8038 RequiresOuterTask](CodeGenFunction &CGF,
8039 PrePostActionTy &) {
8040 if (RequiresOuterTask) {
8041 CapturedVars.clear();
8042 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8043 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008044 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008045 };
8046
8047 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8048 &CapturedVars, RequiresOuterTask,
8049 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8050 // Fill up the arrays with all the captured variables.
8051 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8052 MappableExprsHandler::MapValuesArrayTy Pointers;
8053 MappableExprsHandler::MapValuesArrayTy Sizes;
8054 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8055
Alexey Bataev8451efa2018-01-15 19:06:12 +00008056 // Get mappable expression information.
8057 MappableExprsHandler MEHandler(D, CGF);
8058
8059 auto RI = CS.getCapturedRecordDecl()->field_begin();
8060 auto CV = CapturedVars.begin();
8061 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8062 CE = CS.capture_end();
8063 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008064 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8065 MappableExprsHandler::MapValuesArrayTy CurPointers;
8066 MappableExprsHandler::MapValuesArrayTy CurSizes;
8067 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8068 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008069
8070 // VLA sizes are passed to the outlined region by copy and do not have map
8071 // information associated.
8072 if (CI->capturesVariableArrayType()) {
8073 CurBasePointers.push_back(*CV);
8074 CurPointers.push_back(*CV);
8075 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8076 // Copy to the device as an argument. No need to retrieve it.
8077 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8078 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8079 } else {
8080 // If we have any information in the map clause, we use it, otherwise we
8081 // just do a default mapping.
8082 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008083 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008084 if (CurBasePointers.empty())
8085 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8086 CurPointers, CurSizes, CurMapTypes);
8087 }
8088 // We expect to have at least an element of information for this capture.
8089 assert(!CurBasePointers.empty() &&
8090 "Non-existing map pointer for capture!");
8091 assert(CurBasePointers.size() == CurPointers.size() &&
8092 CurBasePointers.size() == CurSizes.size() &&
8093 CurBasePointers.size() == CurMapTypes.size() &&
8094 "Inconsistent map information sizes!");
8095
Alexey Bataevb3638132018-07-19 16:34:13 +00008096 // If there is an entry in PartialStruct it means we have a struct with
8097 // individual members mapped. Emit an extra combined entry.
8098 if (PartialStruct.Base.isValid())
8099 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8100 CurMapTypes, PartialStruct);
8101
Alexey Bataev8451efa2018-01-15 19:06:12 +00008102 // We need to append the results of this capture to what we already have.
8103 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8104 Pointers.append(CurPointers.begin(), CurPointers.end());
8105 Sizes.append(CurSizes.begin(), CurSizes.end());
8106 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8107 }
Alexey Bataev92327c52018-03-26 16:40:55 +00008108 // Map other list items in the map clause which are not captured variables
8109 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008110 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8111 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008112
8113 TargetDataInfo Info;
8114 // Fill up the arrays and create the arguments.
8115 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8116 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8117 Info.PointersArray, Info.SizesArray,
8118 Info.MapTypesArray, Info);
8119 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8120 InputInfo.BasePointersArray =
8121 Address(Info.BasePointersArray, CGM.getPointerAlign());
8122 InputInfo.PointersArray =
8123 Address(Info.PointersArray, CGM.getPointerAlign());
8124 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8125 MapTypesArray = Info.MapTypesArray;
8126 if (RequiresOuterTask)
8127 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8128 else
8129 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8130 };
8131
8132 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8133 CodeGenFunction &CGF, PrePostActionTy &) {
8134 if (RequiresOuterTask) {
8135 CodeGenFunction::OMPTargetDataInfo InputInfo;
8136 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8137 } else {
8138 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8139 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008140 };
8141
8142 // If we have a target function ID it means that we need to support
8143 // offloading, otherwise, just execute on the host. We need to execute on host
8144 // regardless of the conditional in the if clause if, e.g., the user do not
8145 // specify target triples.
8146 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008147 if (IfCond) {
8148 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8149 } else {
8150 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008151 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008152 }
8153 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008154 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008155 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008156 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008157}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008158
8159void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8160 StringRef ParentName) {
8161 if (!S)
8162 return;
8163
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008164 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008165 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008166 isa<OMPExecutableDirective>(S) &&
8167 isOpenMPTargetExecutionDirective(
8168 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008169
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008170 if (RequiresDeviceCodegen) {
8171 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008172 unsigned DeviceID;
8173 unsigned FileID;
8174 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008175 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008176 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008177
8178 // Is this a target region that should not be emitted as an entry point? If
8179 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008180 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8181 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008182 return;
8183
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008184 switch (E.getDirectiveKind()) {
8185 case OMPD_target:
8186 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8187 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008188 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008189 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008190 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008191 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008192 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008193 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008194 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008195 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008196 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008197 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008198 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008199 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008200 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008201 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008202 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008203 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008204 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008205 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008206 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008207 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008208 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008209 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008210 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008211 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008212 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008213 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008214 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008215 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008216 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008217 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008218 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8219 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008220 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008221 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008222 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008223 CodeGenFunction::
8224 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8225 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008226 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008227 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008228 case OMPD_parallel:
8229 case OMPD_for:
8230 case OMPD_parallel_for:
8231 case OMPD_parallel_sections:
8232 case OMPD_for_simd:
8233 case OMPD_parallel_for_simd:
8234 case OMPD_cancel:
8235 case OMPD_cancellation_point:
8236 case OMPD_ordered:
8237 case OMPD_threadprivate:
8238 case OMPD_task:
8239 case OMPD_simd:
8240 case OMPD_sections:
8241 case OMPD_section:
8242 case OMPD_single:
8243 case OMPD_master:
8244 case OMPD_critical:
8245 case OMPD_taskyield:
8246 case OMPD_barrier:
8247 case OMPD_taskwait:
8248 case OMPD_taskgroup:
8249 case OMPD_atomic:
8250 case OMPD_flush:
8251 case OMPD_teams:
8252 case OMPD_target_data:
8253 case OMPD_target_exit_data:
8254 case OMPD_target_enter_data:
8255 case OMPD_distribute:
8256 case OMPD_distribute_simd:
8257 case OMPD_distribute_parallel_for:
8258 case OMPD_distribute_parallel_for_simd:
8259 case OMPD_teams_distribute:
8260 case OMPD_teams_distribute_simd:
8261 case OMPD_teams_distribute_parallel_for:
8262 case OMPD_teams_distribute_parallel_for_simd:
8263 case OMPD_target_update:
8264 case OMPD_declare_simd:
8265 case OMPD_declare_target:
8266 case OMPD_end_declare_target:
8267 case OMPD_declare_reduction:
8268 case OMPD_taskloop:
8269 case OMPD_taskloop_simd:
8270 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008271 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8272 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008273 return;
8274 }
8275
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008276 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008277 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008278 return;
8279
8280 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008281 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008282 return;
8283 }
8284
8285 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008286 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008287 S = L->getBody();
8288
8289 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008290 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008291 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008292}
8293
8294bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008295 // If emitting code for the host, we do not process FD here. Instead we do
8296 // the normal code generation.
8297 if (!CGM.getLangOpts().OpenMPIsDevice)
8298 return false;
8299
8300 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008301 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
8302 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
8303 scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
Samuel Antaoee8fb302016-01-06 13:42:12 +00008304
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008305 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008306 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
8307 AlreadyEmittedTargetFunctions.count(VD->getCanonicalDecl()) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008308}
8309
8310bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8311 if (!CGM.getLangOpts().OpenMPIsDevice)
8312 return false;
8313
8314 // Check if there are Ctors/Dtors in this declaration and look for target
8315 // regions in it. We use the complete variant to produce the kernel name
8316 // mangling.
8317 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008318 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8319 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008320 StringRef ParentName =
8321 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8322 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8323 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008324 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008325 StringRef ParentName =
8326 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8327 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8328 }
8329 }
8330
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008331 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008332 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008333 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8334 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008335 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008336 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008337 return true;
8338 }
8339 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008340}
8341
Alexey Bataev03f270c2018-03-30 18:31:07 +00008342void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8343 llvm::Constant *Addr) {
8344 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008345 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00008346 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8347 StringRef VarName;
8348 CharUnits VarSize;
8349 llvm::GlobalValue::LinkageTypes Linkage;
8350 switch (*Res) {
8351 case OMPDeclareTargetDeclAttr::MT_To:
8352 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8353 VarName = CGM.getMangledName(VD);
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00008354 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8355 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8356 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8357 } else {
8358 VarSize = CharUnits::Zero();
8359 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00008360 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
Alexey Bataev38235142018-07-31 16:40:15 +00008361 // Temp solution to prevent optimizations of the internal variables.
8362 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8363 std::string RefName = getName({VarName, "ref"});
8364 if (!CGM.GetGlobalValue(RefName)) {
8365 llvm::Constant *AddrRef =
8366 getOrCreateInternalVariable(Addr->getType(), RefName);
8367 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8368 GVAddrRef->setConstant(/*Val=*/true);
8369 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8370 GVAddrRef->setInitializer(Addr);
8371 CGM.addCompilerUsedGlobal(GVAddrRef);
8372 }
8373 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00008374 break;
8375 case OMPDeclareTargetDeclAttr::MT_Link:
Alexey Bataevc52f01d2018-07-16 20:05:25 +00008376 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8377 if (CGM.getLangOpts().OpenMPIsDevice) {
8378 VarName = Addr->getName();
8379 Addr = nullptr;
8380 } else {
8381 VarName = getAddrOfDeclareTargetLink(VD).getName();
Alexey Bataev03f270c2018-03-30 18:31:07 +00008382 Addr =
8383 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8384 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00008385 VarSize = CGM.getPointerSize();
8386 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8387 break;
8388 }
8389 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8390 VarName, Addr, VarSize, Flags, Linkage);
8391 }
8392}
8393
Samuel Antaoee8fb302016-01-06 13:42:12 +00008394bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008395 if (isa<FunctionDecl>(GD.getDecl()) ||
8396 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008397 return emitTargetFunctions(GD);
8398
8399 return emitTargetGlobalVariable(GD);
8400}
8401
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008402void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8403 for (const VarDecl *VD : DeferredGlobalVariables) {
8404 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008405 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008406 if (!Res)
8407 continue;
8408 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008409 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008410 } else {
8411 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8412 "Expected to or link clauses.");
8413 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008414 }
8415 }
8416}
8417
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008418CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8419 CodeGenModule &CGM)
8420 : CGM(CGM) {
8421 if (CGM.getLangOpts().OpenMPIsDevice) {
8422 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8423 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8424 }
8425}
8426
8427CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8428 if (CGM.getLangOpts().OpenMPIsDevice)
8429 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8430}
8431
Alexey Bataev6d944102018-05-02 15:45:28 +00008432bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008433 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8434 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008435
Alexey Bataev6d944102018-05-02 15:45:28 +00008436 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008437 const FunctionDecl *FD = D->getCanonicalDecl();
Alexey Bataev34f8a702018-03-28 14:28:54 +00008438 // Do not to emit function if it is marked as declare target as it was already
8439 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008440 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev34f8a702018-03-28 14:28:54 +00008441 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
8442 if (auto *F = dyn_cast_or_null<llvm::Function>(
Alexey Bataev6d944102018-05-02 15:45:28 +00008443 CGM.GetGlobalValue(CGM.getMangledName(GD))))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008444 return !F->isDeclaration();
8445 return false;
8446 }
8447 return true;
8448 }
8449
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008450 return !AlreadyEmittedTargetFunctions.insert(FD).second;
8451}
8452
Samuel Antaoee8fb302016-01-06 13:42:12 +00008453llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8454 // If we have offloading in the current module, we need to emit the entries
8455 // now and register the offloading descriptor.
8456 createOffloadEntriesAndInfoMetadata();
8457
8458 // Create and register the offloading binary descriptors. This is the main
8459 // entity that captures all the information about offloading in the current
8460 // compilation unit.
8461 return createOffloadingBinaryDescriptorRegistration();
8462}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008463
8464void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8465 const OMPExecutableDirective &D,
8466 SourceLocation Loc,
8467 llvm::Value *OutlinedFn,
8468 ArrayRef<llvm::Value *> CapturedVars) {
8469 if (!CGF.HaveInsertPoint())
8470 return;
8471
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008472 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008473 CodeGenFunction::RunCleanupsScope Scope(CGF);
8474
8475 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8476 llvm::Value *Args[] = {
8477 RTLoc,
8478 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8479 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8480 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8481 RealArgs.append(std::begin(Args), std::end(Args));
8482 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8483
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008484 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008485 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8486}
8487
8488void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008489 const Expr *NumTeams,
8490 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008491 SourceLocation Loc) {
8492 if (!CGF.HaveInsertPoint())
8493 return;
8494
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008495 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008496
Carlo Bertollic6872252016-04-04 15:55:02 +00008497 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008498 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008499 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8500 CGF.CGM.Int32Ty, /* isSigned = */ true)
8501 : CGF.Builder.getInt32(0);
8502
8503 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008504 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008505 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8506 CGF.CGM.Int32Ty, /* isSigned = */ true)
8507 : CGF.Builder.getInt32(0);
8508
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008509 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008510 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8511 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008512 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8513 PushNumTeamsArgs);
8514}
Samuel Antaodf158d52016-04-27 22:58:19 +00008515
Samuel Antaocc10b852016-07-28 14:23:26 +00008516void CGOpenMPRuntime::emitTargetDataCalls(
8517 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8518 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008519 if (!CGF.HaveInsertPoint())
8520 return;
8521
Samuel Antaocc10b852016-07-28 14:23:26 +00008522 // Action used to replace the default codegen action and turn privatization
8523 // off.
8524 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008525
8526 // Generate the code for the opening of the data environment. Capture all the
8527 // arguments of the runtime call by reference because they are used in the
8528 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008529 auto &&BeginThenGen = [this, &D, Device, &Info,
8530 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008531 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008532 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008533 MappableExprsHandler::MapValuesArrayTy Pointers;
8534 MappableExprsHandler::MapValuesArrayTy Sizes;
8535 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8536
8537 // Get map clause information.
8538 MappableExprsHandler MCHandler(D, CGF);
8539 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008540
8541 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008542 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008543
8544 llvm::Value *BasePointersArrayArg = nullptr;
8545 llvm::Value *PointersArrayArg = nullptr;
8546 llvm::Value *SizesArrayArg = nullptr;
8547 llvm::Value *MapTypesArrayArg = nullptr;
8548 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008549 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008550
8551 // Emit device ID if any.
8552 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008553 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008554 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008555 CGF.Int64Ty, /*isSigned=*/true);
8556 } else {
8557 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8558 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008559
8560 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008561 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008562
8563 llvm::Value *OffloadingArgs[] = {
8564 DeviceID, PointerNum, BasePointersArrayArg,
8565 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008566 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008567 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008568
8569 // If device pointer privatization is required, emit the body of the region
8570 // here. It will have to be duplicated: with and without privatization.
8571 if (!Info.CaptureDeviceAddrMap.empty())
8572 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008573 };
8574
8575 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008576 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8577 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008578 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008579
8580 llvm::Value *BasePointersArrayArg = nullptr;
8581 llvm::Value *PointersArrayArg = nullptr;
8582 llvm::Value *SizesArrayArg = nullptr;
8583 llvm::Value *MapTypesArrayArg = nullptr;
8584 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008585 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008586
8587 // Emit device ID if any.
8588 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008589 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008590 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008591 CGF.Int64Ty, /*isSigned=*/true);
8592 } else {
8593 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8594 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008595
8596 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008597 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008598
8599 llvm::Value *OffloadingArgs[] = {
8600 DeviceID, PointerNum, BasePointersArrayArg,
8601 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008602 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008603 OffloadingArgs);
8604 };
8605
Samuel Antaocc10b852016-07-28 14:23:26 +00008606 // If we need device pointer privatization, we need to emit the body of the
8607 // region with no privatization in the 'else' branch of the conditional.
8608 // Otherwise, we don't have to do anything.
8609 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8610 PrePostActionTy &) {
8611 if (!Info.CaptureDeviceAddrMap.empty()) {
8612 CodeGen.setAction(NoPrivAction);
8613 CodeGen(CGF);
8614 }
8615 };
8616
8617 // We don't have to do anything to close the region if the if clause evaluates
8618 // to false.
8619 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008620
8621 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008622 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008623 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008624 RegionCodeGenTy RCG(BeginThenGen);
8625 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008626 }
8627
Samuel Antaocc10b852016-07-28 14:23:26 +00008628 // If we don't require privatization of device pointers, we emit the body in
8629 // between the runtime calls. This avoids duplicating the body code.
8630 if (Info.CaptureDeviceAddrMap.empty()) {
8631 CodeGen.setAction(NoPrivAction);
8632 CodeGen(CGF);
8633 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008634
8635 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008636 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008637 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008638 RegionCodeGenTy RCG(EndThenGen);
8639 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008640 }
8641}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008642
Samuel Antao8d2d7302016-05-26 18:30:22 +00008643void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008644 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8645 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008646 if (!CGF.HaveInsertPoint())
8647 return;
8648
Samuel Antao8dd66282016-04-27 23:14:30 +00008649 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008650 isa<OMPTargetExitDataDirective>(D) ||
8651 isa<OMPTargetUpdateDirective>(D)) &&
8652 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008653
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008654 CodeGenFunction::OMPTargetDataInfo InputInfo;
8655 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008656 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008657 auto &&ThenGen = [this, &D, Device, &InputInfo,
8658 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008659 // Emit device ID if any.
8660 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008661 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008662 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008663 CGF.Int64Ty, /*isSigned=*/true);
8664 } else {
8665 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8666 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008667
8668 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008669 llvm::Constant *PointerNum =
8670 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008671
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008672 llvm::Value *OffloadingArgs[] = {DeviceID,
8673 PointerNum,
8674 InputInfo.BasePointersArray.getPointer(),
8675 InputInfo.PointersArray.getPointer(),
8676 InputInfo.SizesArray.getPointer(),
8677 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008678
Samuel Antao8d2d7302016-05-26 18:30:22 +00008679 // Select the right runtime function call for each expected standalone
8680 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008681 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008682 OpenMPRTLFunction RTLFn;
8683 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008684 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008685 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8686 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008687 break;
8688 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008689 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8690 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008691 break;
8692 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008693 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8694 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008695 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008696 case OMPD_parallel:
8697 case OMPD_for:
8698 case OMPD_parallel_for:
8699 case OMPD_parallel_sections:
8700 case OMPD_for_simd:
8701 case OMPD_parallel_for_simd:
8702 case OMPD_cancel:
8703 case OMPD_cancellation_point:
8704 case OMPD_ordered:
8705 case OMPD_threadprivate:
8706 case OMPD_task:
8707 case OMPD_simd:
8708 case OMPD_sections:
8709 case OMPD_section:
8710 case OMPD_single:
8711 case OMPD_master:
8712 case OMPD_critical:
8713 case OMPD_taskyield:
8714 case OMPD_barrier:
8715 case OMPD_taskwait:
8716 case OMPD_taskgroup:
8717 case OMPD_atomic:
8718 case OMPD_flush:
8719 case OMPD_teams:
8720 case OMPD_target_data:
8721 case OMPD_distribute:
8722 case OMPD_distribute_simd:
8723 case OMPD_distribute_parallel_for:
8724 case OMPD_distribute_parallel_for_simd:
8725 case OMPD_teams_distribute:
8726 case OMPD_teams_distribute_simd:
8727 case OMPD_teams_distribute_parallel_for:
8728 case OMPD_teams_distribute_parallel_for_simd:
8729 case OMPD_declare_simd:
8730 case OMPD_declare_target:
8731 case OMPD_end_declare_target:
8732 case OMPD_declare_reduction:
8733 case OMPD_taskloop:
8734 case OMPD_taskloop_simd:
8735 case OMPD_target:
8736 case OMPD_target_simd:
8737 case OMPD_target_teams_distribute:
8738 case OMPD_target_teams_distribute_simd:
8739 case OMPD_target_teams_distribute_parallel_for:
8740 case OMPD_target_teams_distribute_parallel_for_simd:
8741 case OMPD_target_teams:
8742 case OMPD_target_parallel:
8743 case OMPD_target_parallel_for:
8744 case OMPD_target_parallel_for_simd:
8745 case OMPD_unknown:
8746 llvm_unreachable("Unexpected standalone target data directive.");
8747 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008748 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008749 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008750 };
8751
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008752 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8753 CodeGenFunction &CGF, PrePostActionTy &) {
8754 // Fill up the arrays with all the mapped variables.
8755 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8756 MappableExprsHandler::MapValuesArrayTy Pointers;
8757 MappableExprsHandler::MapValuesArrayTy Sizes;
8758 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008759
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008760 // Get map clause information.
8761 MappableExprsHandler MEHandler(D, CGF);
8762 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8763
8764 TargetDataInfo Info;
8765 // Fill up the arrays and create the arguments.
8766 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8767 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8768 Info.PointersArray, Info.SizesArray,
8769 Info.MapTypesArray, Info);
8770 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8771 InputInfo.BasePointersArray =
8772 Address(Info.BasePointersArray, CGM.getPointerAlign());
8773 InputInfo.PointersArray =
8774 Address(Info.PointersArray, CGM.getPointerAlign());
8775 InputInfo.SizesArray =
8776 Address(Info.SizesArray, CGM.getPointerAlign());
8777 MapTypesArray = Info.MapTypesArray;
8778 if (D.hasClausesOfKind<OMPDependClause>())
8779 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8780 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008781 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008782 };
8783
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008784 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008785 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8786 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008787 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008788 RegionCodeGenTy ThenRCG(TargetThenGen);
8789 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008790 }
8791}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008792
8793namespace {
8794 /// Kind of parameter in a function with 'declare simd' directive.
8795 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8796 /// Attribute set of the parameter.
8797 struct ParamAttrTy {
8798 ParamKindTy Kind = Vector;
8799 llvm::APSInt StrideOrArg;
8800 llvm::APSInt Alignment;
8801 };
8802} // namespace
8803
8804static unsigned evaluateCDTSize(const FunctionDecl *FD,
8805 ArrayRef<ParamAttrTy> ParamAttrs) {
8806 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8807 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8808 // of that clause. The VLEN value must be power of 2.
8809 // In other case the notion of the function`s "characteristic data type" (CDT)
8810 // is used to compute the vector length.
8811 // CDT is defined in the following order:
8812 // a) For non-void function, the CDT is the return type.
8813 // b) If the function has any non-uniform, non-linear parameters, then the
8814 // CDT is the type of the first such parameter.
8815 // c) If the CDT determined by a) or b) above is struct, union, or class
8816 // type which is pass-by-value (except for the type that maps to the
8817 // built-in complex data type), the characteristic data type is int.
8818 // d) If none of the above three cases is applicable, the CDT is int.
8819 // The VLEN is then determined based on the CDT and the size of vector
8820 // register of that ISA for which current vector version is generated. The
8821 // VLEN is computed using the formula below:
8822 // VLEN = sizeof(vector_register) / sizeof(CDT),
8823 // where vector register size specified in section 3.2.1 Registers and the
8824 // Stack Frame of original AMD64 ABI document.
8825 QualType RetType = FD->getReturnType();
8826 if (RetType.isNull())
8827 return 0;
8828 ASTContext &C = FD->getASTContext();
8829 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008830 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008831 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008832 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008833 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008834 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008835 if (ParamAttrs[Offset].Kind == Vector)
8836 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8837 ++Offset;
8838 }
8839 if (CDT.isNull()) {
8840 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8841 if (ParamAttrs[I + Offset].Kind == Vector) {
8842 CDT = FD->getParamDecl(I)->getType();
8843 break;
8844 }
8845 }
8846 }
8847 }
8848 if (CDT.isNull())
8849 CDT = C.IntTy;
8850 CDT = CDT->getCanonicalTypeUnqualified();
8851 if (CDT->isRecordType() || CDT->isUnionType())
8852 CDT = C.IntTy;
8853 return C.getTypeSize(CDT);
8854}
8855
8856static void
8857emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00008858 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008859 ArrayRef<ParamAttrTy> ParamAttrs,
8860 OMPDeclareSimdDeclAttr::BranchStateTy State) {
8861 struct ISADataTy {
8862 char ISA;
8863 unsigned VecRegSize;
8864 };
8865 ISADataTy ISAData[] = {
8866 {
8867 'b', 128
8868 }, // SSE
8869 {
8870 'c', 256
8871 }, // AVX
8872 {
8873 'd', 256
8874 }, // AVX2
8875 {
8876 'e', 512
8877 }, // AVX512
8878 };
8879 llvm::SmallVector<char, 2> Masked;
8880 switch (State) {
8881 case OMPDeclareSimdDeclAttr::BS_Undefined:
8882 Masked.push_back('N');
8883 Masked.push_back('M');
8884 break;
8885 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
8886 Masked.push_back('N');
8887 break;
8888 case OMPDeclareSimdDeclAttr::BS_Inbranch:
8889 Masked.push_back('M');
8890 break;
8891 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008892 for (char Mask : Masked) {
8893 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008894 SmallString<256> Buffer;
8895 llvm::raw_svector_ostream Out(Buffer);
8896 Out << "_ZGV" << Data.ISA << Mask;
8897 if (!VLENVal) {
8898 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
8899 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008900 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008901 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008902 }
8903 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008904 switch (ParamAttr.Kind){
8905 case LinearWithVarStride:
8906 Out << 's' << ParamAttr.StrideOrArg;
8907 break;
8908 case Linear:
8909 Out << 'l';
8910 if (!!ParamAttr.StrideOrArg)
8911 Out << ParamAttr.StrideOrArg;
8912 break;
8913 case Uniform:
8914 Out << 'u';
8915 break;
8916 case Vector:
8917 Out << 'v';
8918 break;
8919 }
8920 if (!!ParamAttr.Alignment)
8921 Out << 'a' << ParamAttr.Alignment;
8922 }
8923 Out << '_' << Fn->getName();
8924 Fn->addFnAttr(Out.str());
8925 }
8926 }
8927}
8928
8929void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
8930 llvm::Function *Fn) {
8931 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008932 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008933 // Map params to their positions in function decl.
8934 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
8935 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008936 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008937 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008938 for (const ParmVarDecl *P : FD->parameters()) {
8939 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008940 ++ParamPos;
8941 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008942 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008943 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008944 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
8945 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008946 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008947 E = E->IgnoreParenImpCasts();
8948 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008949 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008950 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008951 } else {
8952 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8953 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008954 Pos = ParamPositions[PVD];
8955 }
8956 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008957 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008958 // Get alignment info.
8959 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008960 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008961 E = E->IgnoreParenImpCasts();
8962 unsigned Pos;
8963 QualType ParmTy;
8964 if (isa<CXXThisExpr>(E)) {
8965 Pos = ParamPositions[FD];
8966 ParmTy = E->getType();
8967 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008968 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8969 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008970 Pos = ParamPositions[PVD];
8971 ParmTy = PVD->getType();
8972 }
8973 ParamAttrs[Pos].Alignment =
8974 (*NI)
8975 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008976 : llvm::APSInt::getUnsigned(
8977 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8978 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008979 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008980 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008981 // Mark linear parameters.
8982 auto SI = Attr->steps_begin();
8983 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008984 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008985 E = E->IgnoreParenImpCasts();
8986 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008987 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008988 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008989 } else {
8990 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8991 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008992 Pos = ParamPositions[PVD];
8993 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008994 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008995 ParamAttr.Kind = Linear;
8996 if (*SI) {
8997 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8998 Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008999 if (const auto *DRE =
9000 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9001 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009002 ParamAttr.Kind = LinearWithVarStride;
9003 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9004 ParamPositions[StridePVD->getCanonicalDecl()]);
9005 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009006 }
9007 }
9008 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009009 ++SI;
9010 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009011 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009012 llvm::APSInt VLENVal;
9013 if (const Expr *VLEN = Attr->getSimdlen())
9014 VLENVal = VLEN->EvaluateKnownConstInt(C);
9015 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9016 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9017 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9018 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009019 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009020 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009021 }
9022}
Alexey Bataev8b427062016-05-25 12:36:08 +00009023
9024namespace {
9025/// Cleanup action for doacross support.
9026class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9027public:
9028 static const int DoacrossFinArgs = 2;
9029
9030private:
9031 llvm::Value *RTLFn;
9032 llvm::Value *Args[DoacrossFinArgs];
9033
9034public:
9035 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
9036 : RTLFn(RTLFn) {
9037 assert(CallArgs.size() == DoacrossFinArgs);
9038 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9039 }
9040 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9041 if (!CGF.HaveInsertPoint())
9042 return;
9043 CGF.EmitRuntimeCall(RTLFn, Args);
9044 }
9045};
9046} // namespace
9047
9048void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009049 const OMPLoopDirective &D,
9050 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009051 if (!CGF.HaveInsertPoint())
9052 return;
9053
9054 ASTContext &C = CGM.getContext();
9055 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9056 RecordDecl *RD;
9057 if (KmpDimTy.isNull()) {
9058 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9059 // kmp_int64 lo; // lower
9060 // kmp_int64 up; // upper
9061 // kmp_int64 st; // stride
9062 // };
9063 RD = C.buildImplicitRecord("kmp_dim");
9064 RD->startDefinition();
9065 addFieldToRecordDecl(C, RD, Int64Ty);
9066 addFieldToRecordDecl(C, RD, Int64Ty);
9067 addFieldToRecordDecl(C, RD, Int64Ty);
9068 RD->completeDefinition();
9069 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009070 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009071 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009072 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009073 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9074 QualType ArrayTy =
9075 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009076
Alexey Bataevf138fda2018-08-13 19:04:24 +00009077 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9078 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009079 enum { LowerFD = 0, UpperFD, StrideFD };
9080 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009081 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
9082 LValue DimsLVal =
9083 CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP(
9084 DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)),
9085 KmpDimTy);
9086 // dims.upper = num_iterations;
9087 LValue UpperLVal = CGF.EmitLValueForField(
9088 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9089 llvm::Value *NumIterVal =
9090 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9091 D.getNumIterations()->getType(), Int64Ty,
9092 D.getNumIterations()->getExprLoc());
9093 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9094 // dims.stride = 1;
9095 LValue StrideLVal = CGF.EmitLValueForField(
9096 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9097 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9098 StrideLVal);
9099 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009100
9101 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9102 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009103 llvm::Value *Args[] = {
9104 emitUpdateLocation(CGF, D.getBeginLoc()),
9105 getThreadID(CGF, D.getBeginLoc()),
9106 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9107 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
9108 CGF.Builder
9109 .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy))
9110 .getPointer(),
9111 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009112
9113 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
9114 CGF.EmitRuntimeCall(RTLFn, Args);
9115 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009116 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
Alexey Bataev8b427062016-05-25 12:36:08 +00009117 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
9118 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9119 llvm::makeArrayRef(FiniArgs));
9120}
9121
9122void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9123 const OMPDependClause *C) {
9124 QualType Int64Ty =
9125 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009126 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9127 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9128 Int64Ty, Size, ArrayType::Normal, 0);
9129 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9130 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9131 const Expr *CounterVal = C->getLoopData(I);
9132 assert(CounterVal);
9133 llvm::Value *CntVal = CGF.EmitScalarConversion(
9134 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9135 CounterVal->getExprLoc());
9136 CGF.EmitStoreOfScalar(
9137 CntVal,
9138 CGF.Builder.CreateConstArrayGEP(
9139 CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)),
9140 /*Volatile=*/false, Int64Ty);
9141 }
9142 llvm::Value *Args[] = {
9143 emitUpdateLocation(CGF, C->getBeginLoc()),
9144 getThreadID(CGF, C->getBeginLoc()),
9145 CGF.Builder
9146 .CreateConstArrayGEP(CntAddr, 0,
9147 CGM.getContext().getTypeSizeInChars(Int64Ty))
9148 .getPointer()};
Alexey Bataev8b427062016-05-25 12:36:08 +00009149 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009150 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009151 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009152 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009153 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9154 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9155 }
9156 CGF.EmitRuntimeCall(RTLFn, Args);
9157}
9158
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009159void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
9160 llvm::Value *Callee,
9161 ArrayRef<llvm::Value *> Args) const {
9162 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009163 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9164
9165 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009166 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009167 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009168 return;
9169 }
9170 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009171 CGF.EmitRuntimeCall(Callee, Args);
9172}
9173
9174void CGOpenMPRuntime::emitOutlinedFunctionCall(
9175 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
9176 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009177 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009178}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009179
9180Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9181 const VarDecl *NativeParam,
9182 const VarDecl *TargetParam) const {
9183 return CGF.GetAddrOfLocalVar(NativeParam);
9184}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009185
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009186Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9187 const VarDecl *VD) {
9188 return Address::invalid();
9189}
9190
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009191llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
9192 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9193 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9194 llvm_unreachable("Not supported in SIMD-only mode");
9195}
9196
9197llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
9198 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9199 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9200 llvm_unreachable("Not supported in SIMD-only mode");
9201}
9202
9203llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
9204 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9205 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9206 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9207 bool Tied, unsigned &NumberOfParts) {
9208 llvm_unreachable("Not supported in SIMD-only mode");
9209}
9210
9211void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9212 SourceLocation Loc,
9213 llvm::Value *OutlinedFn,
9214 ArrayRef<llvm::Value *> CapturedVars,
9215 const Expr *IfCond) {
9216 llvm_unreachable("Not supported in SIMD-only mode");
9217}
9218
9219void CGOpenMPSIMDRuntime::emitCriticalRegion(
9220 CodeGenFunction &CGF, StringRef CriticalName,
9221 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9222 const Expr *Hint) {
9223 llvm_unreachable("Not supported in SIMD-only mode");
9224}
9225
9226void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9227 const RegionCodeGenTy &MasterOpGen,
9228 SourceLocation Loc) {
9229 llvm_unreachable("Not supported in SIMD-only mode");
9230}
9231
9232void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9233 SourceLocation Loc) {
9234 llvm_unreachable("Not supported in SIMD-only mode");
9235}
9236
9237void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9238 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9239 SourceLocation Loc) {
9240 llvm_unreachable("Not supported in SIMD-only mode");
9241}
9242
9243void CGOpenMPSIMDRuntime::emitSingleRegion(
9244 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9245 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9246 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9247 ArrayRef<const Expr *> AssignmentOps) {
9248 llvm_unreachable("Not supported in SIMD-only mode");
9249}
9250
9251void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9252 const RegionCodeGenTy &OrderedOpGen,
9253 SourceLocation Loc,
9254 bool IsThreads) {
9255 llvm_unreachable("Not supported in SIMD-only mode");
9256}
9257
9258void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9259 SourceLocation Loc,
9260 OpenMPDirectiveKind Kind,
9261 bool EmitChecks,
9262 bool ForceSimpleCall) {
9263 llvm_unreachable("Not supported in SIMD-only mode");
9264}
9265
9266void CGOpenMPSIMDRuntime::emitForDispatchInit(
9267 CodeGenFunction &CGF, SourceLocation Loc,
9268 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9269 bool Ordered, const DispatchRTInput &DispatchValues) {
9270 llvm_unreachable("Not supported in SIMD-only mode");
9271}
9272
9273void CGOpenMPSIMDRuntime::emitForStaticInit(
9274 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9275 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9276 llvm_unreachable("Not supported in SIMD-only mode");
9277}
9278
9279void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9280 CodeGenFunction &CGF, SourceLocation Loc,
9281 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9282 llvm_unreachable("Not supported in SIMD-only mode");
9283}
9284
9285void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9286 SourceLocation Loc,
9287 unsigned IVSize,
9288 bool IVSigned) {
9289 llvm_unreachable("Not supported in SIMD-only mode");
9290}
9291
9292void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9293 SourceLocation Loc,
9294 OpenMPDirectiveKind DKind) {
9295 llvm_unreachable("Not supported in SIMD-only mode");
9296}
9297
9298llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9299 SourceLocation Loc,
9300 unsigned IVSize, bool IVSigned,
9301 Address IL, Address LB,
9302 Address UB, Address ST) {
9303 llvm_unreachable("Not supported in SIMD-only mode");
9304}
9305
9306void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9307 llvm::Value *NumThreads,
9308 SourceLocation Loc) {
9309 llvm_unreachable("Not supported in SIMD-only mode");
9310}
9311
9312void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9313 OpenMPProcBindClauseKind ProcBind,
9314 SourceLocation Loc) {
9315 llvm_unreachable("Not supported in SIMD-only mode");
9316}
9317
9318Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9319 const VarDecl *VD,
9320 Address VDAddr,
9321 SourceLocation Loc) {
9322 llvm_unreachable("Not supported in SIMD-only mode");
9323}
9324
9325llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9326 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9327 CodeGenFunction *CGF) {
9328 llvm_unreachable("Not supported in SIMD-only mode");
9329}
9330
9331Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9332 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9333 llvm_unreachable("Not supported in SIMD-only mode");
9334}
9335
9336void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9337 ArrayRef<const Expr *> Vars,
9338 SourceLocation Loc) {
9339 llvm_unreachable("Not supported in SIMD-only mode");
9340}
9341
9342void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9343 const OMPExecutableDirective &D,
9344 llvm::Value *TaskFunction,
9345 QualType SharedsTy, Address Shareds,
9346 const Expr *IfCond,
9347 const OMPTaskDataTy &Data) {
9348 llvm_unreachable("Not supported in SIMD-only mode");
9349}
9350
9351void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9352 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
9353 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
9354 const Expr *IfCond, const OMPTaskDataTy &Data) {
9355 llvm_unreachable("Not supported in SIMD-only mode");
9356}
9357
9358void CGOpenMPSIMDRuntime::emitReduction(
9359 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9360 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9361 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9362 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9363 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9364 ReductionOps, Options);
9365}
9366
9367llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9368 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9369 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9370 llvm_unreachable("Not supported in SIMD-only mode");
9371}
9372
9373void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9374 SourceLocation Loc,
9375 ReductionCodeGen &RCG,
9376 unsigned N) {
9377 llvm_unreachable("Not supported in SIMD-only mode");
9378}
9379
9380Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9381 SourceLocation Loc,
9382 llvm::Value *ReductionsPtr,
9383 LValue SharedLVal) {
9384 llvm_unreachable("Not supported in SIMD-only mode");
9385}
9386
9387void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9388 SourceLocation Loc) {
9389 llvm_unreachable("Not supported in SIMD-only mode");
9390}
9391
9392void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9393 CodeGenFunction &CGF, SourceLocation Loc,
9394 OpenMPDirectiveKind CancelRegion) {
9395 llvm_unreachable("Not supported in SIMD-only mode");
9396}
9397
9398void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9399 SourceLocation Loc, const Expr *IfCond,
9400 OpenMPDirectiveKind CancelRegion) {
9401 llvm_unreachable("Not supported in SIMD-only mode");
9402}
9403
9404void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9405 const OMPExecutableDirective &D, StringRef ParentName,
9406 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9407 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9408 llvm_unreachable("Not supported in SIMD-only mode");
9409}
9410
9411void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9412 const OMPExecutableDirective &D,
9413 llvm::Value *OutlinedFn,
9414 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00009415 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009416 llvm_unreachable("Not supported in SIMD-only mode");
9417}
9418
9419bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9420 llvm_unreachable("Not supported in SIMD-only mode");
9421}
9422
9423bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9424 llvm_unreachable("Not supported in SIMD-only mode");
9425}
9426
9427bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9428 return false;
9429}
9430
9431llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9432 return nullptr;
9433}
9434
9435void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9436 const OMPExecutableDirective &D,
9437 SourceLocation Loc,
9438 llvm::Value *OutlinedFn,
9439 ArrayRef<llvm::Value *> CapturedVars) {
9440 llvm_unreachable("Not supported in SIMD-only mode");
9441}
9442
9443void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9444 const Expr *NumTeams,
9445 const Expr *ThreadLimit,
9446 SourceLocation Loc) {
9447 llvm_unreachable("Not supported in SIMD-only mode");
9448}
9449
9450void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9451 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9452 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9453 llvm_unreachable("Not supported in SIMD-only mode");
9454}
9455
9456void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9457 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9458 const Expr *Device) {
9459 llvm_unreachable("Not supported in SIMD-only mode");
9460}
9461
9462void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009463 const OMPLoopDirective &D,
9464 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009465 llvm_unreachable("Not supported in SIMD-only mode");
9466}
9467
9468void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9469 const OMPDependClause *C) {
9470 llvm_unreachable("Not supported in SIMD-only mode");
9471}
9472
9473const VarDecl *
9474CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9475 const VarDecl *NativeParam) const {
9476 llvm_unreachable("Not supported in SIMD-only mode");
9477}
9478
9479Address
9480CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9481 const VarDecl *NativeParam,
9482 const VarDecl *TargetParam) const {
9483 llvm_unreachable("Not supported in SIMD-only mode");
9484}
9485