blob: f8314194f6726933231f9937ba721ab17e1b51fa [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataev9959db52014-05-06 10:08:46 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for OpenMP runtime code generation.
10//
11//===----------------------------------------------------------------------===//
12
Samuel Antaoee8fb302016-01-06 13:42:12 +000013#include "CGCXXABI.h"
14#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +000016#include "CGRecordLayout.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000017#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Richard Smithbf5bcf22018-06-26 23:20:26 +000021#include "clang/Basic/BitmaskEnum.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022#include "llvm/ADT/ArrayRef.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000024#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000028#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000029#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000030#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000031
32using namespace clang;
33using namespace CodeGen;
34
Benjamin Kramerc52193f2014-10-10 13:57:57 +000035namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000036/// Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000037class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000039 /// Kinds of OpenMP regions used in codegen.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000040 enum CGOpenMPRegionKind {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000041 /// Region with outlined function for standalone 'parallel'
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000042 /// directive.
43 ParallelOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044 /// Region with outlined function for standalone 'task' directive.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000045 TaskOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 /// Region for constructs that do not require function outlining,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000047 /// like 'for', 'sections', 'atomic' etc. directives.
48 InlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000049 /// Region with outlined function for standalone 'target' directive.
Samuel Antaobed3c462015-10-02 16:14:20 +000050 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 };
Alexey Bataev18095712014-10-10 12:19:54 +000052
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000053 CGOpenMPRegionInfo(const CapturedStmt &CS,
54 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000055 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000058 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000059
60 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000061 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000063 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000064 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000065
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000066 /// Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000067 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000068 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000069
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000070 /// Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000071 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000072
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000073 /// Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000074 /// \return LValue for thread id variable. This LValue always has type int32*.
75 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000076
Alexey Bataev48591dd2016-04-20 04:01:36 +000077 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000079 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080
Alexey Bataev81c7ea02015-07-03 09:56:58 +000081 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82
Alexey Bataev25e5b442015-09-15 12:52:43 +000083 bool hasCancel() const { return HasCancel; }
84
Alexey Bataev18095712014-10-10 12:19:54 +000085 static bool classof(const CGCapturedStmtInfo *Info) {
86 return Info->getKind() == CR_OpenMP;
87 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000088
Alexey Bataev48591dd2016-04-20 04:01:36 +000089 ~CGOpenMPRegionInfo() override = default;
90
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000091protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000092 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000093 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000094 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000095 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096};
Alexey Bataev18095712014-10-10 12:19:54 +000097
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000098/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000099class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000100public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000101 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000102 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000103 OpenMPDirectiveKind Kind, bool HasCancel,
104 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000105 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000107 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000110
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000111 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000112 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000113 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000115 /// Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000116 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000117
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000118 static bool classof(const CGCapturedStmtInfo *Info) {
119 return CGOpenMPRegionInfo::classof(Info) &&
120 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121 ParallelOutlinedRegion;
122 }
123
Alexey Bataev18095712014-10-10 12:19:54 +0000124private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000125 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev18095712014-10-10 12:19:54 +0000126 /// constructs.
127 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000128 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000129};
130
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000131/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000132class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000134 class UntiedTaskActionTy final : public PrePostActionTy {
135 bool Untied;
136 const VarDecl *PartIDVar;
137 const RegionCodeGenTy UntiedCodeGen;
138 llvm::SwitchInst *UntiedSwitch = nullptr;
139
140 public:
141 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142 const RegionCodeGenTy &UntiedCodeGen)
143 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144 void Enter(CodeGenFunction &CGF) override {
145 if (Untied) {
146 // Emit task switching point.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000147 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000148 CGF.GetAddrOfLocalVar(PartIDVar),
149 PartIDVar->getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000150 llvm::Value *Res =
151 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
152 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
Alexey Bataev48591dd2016-04-20 04:01:36 +0000153 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
154 CGF.EmitBlock(DoneBB);
155 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
156 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
157 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
158 CGF.Builder.GetInsertBlock());
159 emitUntiedSwitch(CGF);
160 }
161 }
162 void emitUntiedSwitch(CodeGenFunction &CGF) const {
163 if (Untied) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000164 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000165 CGF.GetAddrOfLocalVar(PartIDVar),
166 PartIDVar->getType()->castAs<PointerType>());
167 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
168 PartIdLVal);
169 UntiedCodeGen(CGF);
170 CodeGenFunction::JumpDest CurPoint =
171 CGF.getJumpDestInCurrentScope(".untied.next.");
172 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
173 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
174 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
175 CGF.Builder.GetInsertBlock());
176 CGF.EmitBranchThroughCleanup(CurPoint);
177 CGF.EmitBlock(CurPoint.getBlock());
178 }
179 }
180 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
181 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000182 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000183 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000184 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000185 OpenMPDirectiveKind Kind, bool HasCancel,
186 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000187 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000188 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000189 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
190 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000191
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000192 /// Get a variable or parameter for storing global thread id
Alexey Bataev62b63b12015-03-10 07:28:44 +0000193 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000194 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000196 /// Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000197 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000198
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000199 /// Get the name of the capture helper.
Alexey Bataev62b63b12015-03-10 07:28:44 +0000200 StringRef getHelperName() const override { return ".omp_outlined."; }
201
Alexey Bataev48591dd2016-04-20 04:01:36 +0000202 void emitUntiedSwitch(CodeGenFunction &CGF) override {
203 Action.emitUntiedSwitch(CGF);
204 }
205
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000206 static bool classof(const CGCapturedStmtInfo *Info) {
207 return CGOpenMPRegionInfo::classof(Info) &&
208 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
209 TaskOutlinedRegion;
210 }
211
Alexey Bataev62b63b12015-03-10 07:28:44 +0000212private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000213 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev62b63b12015-03-10 07:28:44 +0000214 /// constructs.
215 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000216 /// Action for emitting code for untied tasks.
217 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000218};
219
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000220/// API for inlined captured statement code generation in OpenMP
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000221/// constructs.
222class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
223public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000224 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000225 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000226 OpenMPDirectiveKind Kind, bool HasCancel)
227 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
228 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000229 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000230
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000231 // Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000232 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000233 if (OuterRegionInfo)
234 return OuterRegionInfo->getContextValue();
235 llvm_unreachable("No context value for inlined OpenMP region");
236 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000237
Hans Wennborg7eb54642015-09-10 17:07:54 +0000238 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000239 if (OuterRegionInfo) {
240 OuterRegionInfo->setContextValue(V);
241 return;
242 }
243 llvm_unreachable("No context value for inlined OpenMP region");
244 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000245
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000246 /// Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000247 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000248 if (OuterRegionInfo)
249 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000250 // If there is no outer outlined region,no need to lookup in a list of
251 // captured variables, we can use the original one.
252 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000253 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000254
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000255 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000256 if (OuterRegionInfo)
257 return OuterRegionInfo->getThisFieldDecl();
258 return nullptr;
259 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000260
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000261 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000262 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000263 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000264 if (OuterRegionInfo)
265 return OuterRegionInfo->getThreadIDVariable();
266 return nullptr;
267 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000268
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000269 /// Get an LValue for the current ThreadID variable.
Alexey Bataev311a9282017-10-12 13:51:32 +0000270 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
271 if (OuterRegionInfo)
272 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
273 llvm_unreachable("No LValue for inlined OpenMP construct");
274 }
275
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000276 /// Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000277 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000278 if (auto *OuterRegionInfo = getOldCSI())
279 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000280 llvm_unreachable("No helper name for inlined OpenMP construct");
281 }
282
Alexey Bataev48591dd2016-04-20 04:01:36 +0000283 void emitUntiedSwitch(CodeGenFunction &CGF) override {
284 if (OuterRegionInfo)
285 OuterRegionInfo->emitUntiedSwitch(CGF);
286 }
287
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000288 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
289
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000290 static bool classof(const CGCapturedStmtInfo *Info) {
291 return CGOpenMPRegionInfo::classof(Info) &&
292 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
293 }
294
Alexey Bataev48591dd2016-04-20 04:01:36 +0000295 ~CGOpenMPInlinedRegionInfo() override = default;
296
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000297private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000298 /// CodeGen info about outer OpenMP region.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000299 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
300 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000301};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000302
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000303/// API for captured statement code generation in OpenMP target
Samuel Antaobed3c462015-10-02 16:14:20 +0000304/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000305/// captured fields. The name of the target region has to be unique in a given
306/// application so it is provided by the client, because only the client has
307/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000308class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000309public:
310 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000311 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000312 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000313 /*HasCancel=*/false),
314 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000315
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000316 /// This is unused for target regions because each starts executing
Samuel Antaobed3c462015-10-02 16:14:20 +0000317 /// with a single thread.
318 const VarDecl *getThreadIDVariable() const override { return nullptr; }
319
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000320 /// Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000321 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000322
323 static bool classof(const CGCapturedStmtInfo *Info) {
324 return CGOpenMPRegionInfo::classof(Info) &&
325 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
326 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000327
328private:
329 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000330};
331
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000332static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000333 llvm_unreachable("No codegen for expressions");
334}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000335/// API for generation of expressions captured in a innermost OpenMP
Samuel Antaob68e2db2016-03-03 16:20:23 +0000336/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000337class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000338public:
339 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
340 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
341 OMPD_unknown,
342 /*HasCancel=*/false),
343 PrivScope(CGF) {
344 // Make sure the globals captured in the provided statement are local by
345 // using the privatization logic. We assume the same variable is not
346 // captured more than once.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000347 for (const auto &C : CS.captures()) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000348 if (!C.capturesVariable() && !C.capturesVariableByCopy())
349 continue;
350
351 const VarDecl *VD = C.getCapturedVar();
352 if (VD->isLocalVarDeclOrParm())
353 continue;
354
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000355 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Samuel Antaob68e2db2016-03-03 16:20:23 +0000356 /*RefersToEnclosingVariableOrCapture=*/false,
357 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000358 C.getLocation());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000359 PrivScope.addPrivate(
360 VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
Samuel Antaob68e2db2016-03-03 16:20:23 +0000361 }
362 (void)PrivScope.Privatize();
363 }
364
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000365 /// Lookup the captured field decl for a variable.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000366 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000367 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
Samuel Antaob68e2db2016-03-03 16:20:23 +0000368 return FD;
369 return nullptr;
370 }
371
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000372 /// Emit the captured statement body.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000373 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
374 llvm_unreachable("No body for expressions");
375 }
376
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000377 /// Get a variable or parameter for storing global thread id
Samuel Antaob68e2db2016-03-03 16:20:23 +0000378 /// inside OpenMP construct.
379 const VarDecl *getThreadIDVariable() const override {
380 llvm_unreachable("No thread id for expressions");
381 }
382
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000383 /// Get the name of the capture helper.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000384 StringRef getHelperName() const override {
385 llvm_unreachable("No helper name for expressions");
386 }
387
388 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
389
390private:
391 /// Private scope to capture global variables.
392 CodeGenFunction::OMPPrivateScope PrivScope;
393};
394
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000395/// RAII for emitting code of OpenMP constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000396class InlinedOpenMPRegionRAII {
397 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000398 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
399 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000400 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000401
402public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000403 /// Constructs region for combined constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000404 /// \param CodeGen Code generation sequence for combined directives. Includes
405 /// a list of functions used for code generation of implicitly inlined
406 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000407 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000408 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000409 : CGF(CGF) {
410 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000411 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
412 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000413 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
414 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
415 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000416 BlockInfo = CGF.BlockInfo;
417 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000418 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000419
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000420 ~InlinedOpenMPRegionRAII() {
421 // Restore original CapturedStmtInfo only if we're done with code emission.
422 auto *OldCSI =
423 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
424 delete CGF.CapturedStmtInfo;
425 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000426 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
427 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000428 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000429 }
430};
431
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432/// Values for bit flags used in the ident_t to describe the fields.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000433/// All enumeric elements are named and described in accordance with the code
434/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000435enum OpenMPLocationFlags : unsigned {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000436 /// Use trampoline for internal microtask.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000437 OMP_IDENT_IMD = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000438 /// Use c-style ident structure.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000439 OMP_IDENT_KMPC = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000440 /// Atomic reduction option for kmpc_reduce.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000441 OMP_ATOMIC_REDUCE = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000442 /// Explicit 'barrier' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000443 OMP_IDENT_BARRIER_EXPL = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000444 /// Implicit barrier in code.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000445 OMP_IDENT_BARRIER_IMPL = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000446 /// Implicit barrier in 'for' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000447 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000448 /// Implicit barrier in 'sections' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000449 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000450 /// Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000451 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
452 /// Call of __kmp_for_static_init for static loop.
453 OMP_IDENT_WORK_LOOP = 0x200,
454 /// Call of __kmp_for_static_init for sections.
455 OMP_IDENT_WORK_SECTIONS = 0x400,
456 /// Call of __kmp_for_static_init for distribute.
457 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
458 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000459};
460
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000461/// Describes ident structure that describes a source location.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000462/// All descriptions are taken from
463/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
464/// Original structure:
465/// typedef struct ident {
466/// kmp_int32 reserved_1; /**< might be used in Fortran;
467/// see above */
468/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
469/// KMP_IDENT_KMPC identifies this union
470/// member */
471/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
472/// see above */
473///#if USE_ITT_BUILD
474/// /* but currently used for storing
475/// region-specific ITT */
476/// /* contextual information. */
477///#endif /* USE_ITT_BUILD */
478/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
479/// C++ */
480/// char const *psource; /**< String describing the source location.
481/// The string is composed of semi-colon separated
482// fields which describe the source file,
483/// the function and a pair of line numbers that
484/// delimit the construct.
485/// */
486/// } ident_t;
487enum IdentFieldIndex {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000488 /// might be used in Fortran
Alexey Bataev50b3c952016-02-19 10:38:26 +0000489 IdentField_Reserved_1,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000490 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000491 IdentField_Flags,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000492 /// Not really used in Fortran any more
Alexey Bataev50b3c952016-02-19 10:38:26 +0000493 IdentField_Reserved_2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000494 /// Source[4] in Fortran, do not use for C++
Alexey Bataev50b3c952016-02-19 10:38:26 +0000495 IdentField_Reserved_3,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000496 /// String describing the source location. The string is composed of
Alexey Bataev50b3c952016-02-19 10:38:26 +0000497 /// semi-colon separated fields which describe the source file, the function
498 /// and a pair of line numbers that delimit the construct.
499 IdentField_PSource
500};
501
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000502/// Schedule types for 'omp for' loops (these enumerators are taken from
Alexey Bataev50b3c952016-02-19 10:38:26 +0000503/// the enum sched_type in kmp.h).
504enum OpenMPSchedType {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000505 /// Lower bound for default (unordered) versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000506 OMP_sch_lower = 32,
507 OMP_sch_static_chunked = 33,
508 OMP_sch_static = 34,
509 OMP_sch_dynamic_chunked = 35,
510 OMP_sch_guided_chunked = 36,
511 OMP_sch_runtime = 37,
512 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000513 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000514 OMP_sch_static_balanced_chunked = 45,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000515 /// Lower bound for 'ordered' versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000516 OMP_ord_lower = 64,
517 OMP_ord_static_chunked = 65,
518 OMP_ord_static = 66,
519 OMP_ord_dynamic_chunked = 67,
520 OMP_ord_guided_chunked = 68,
521 OMP_ord_runtime = 69,
522 OMP_ord_auto = 70,
523 OMP_sch_default = OMP_sch_static,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000524 /// dist_schedule types
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000525 OMP_dist_sch_static_chunked = 91,
526 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000527 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
528 /// Set if the monotonic schedule modifier was present.
529 OMP_sch_modifier_monotonic = (1 << 29),
530 /// Set if the nonmonotonic schedule modifier was present.
531 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000532};
533
534enum OpenMPRTLFunction {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000535 /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000536 /// kmpc_micro microtask, ...);
537 OMPRTL__kmpc_fork_call,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000538 /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000539 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
540 OMPRTL__kmpc_threadprivate_cached,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000541 /// Call to void __kmpc_threadprivate_register( ident_t *,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000542 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
543 OMPRTL__kmpc_threadprivate_register,
544 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
545 OMPRTL__kmpc_global_thread_num,
546 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
547 // kmp_critical_name *crit);
548 OMPRTL__kmpc_critical,
549 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
550 // global_tid, kmp_critical_name *crit, uintptr_t hint);
551 OMPRTL__kmpc_critical_with_hint,
552 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
553 // kmp_critical_name *crit);
554 OMPRTL__kmpc_end_critical,
555 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
556 // global_tid);
557 OMPRTL__kmpc_cancel_barrier,
558 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
559 OMPRTL__kmpc_barrier,
560 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
561 OMPRTL__kmpc_for_static_fini,
562 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
563 // global_tid);
564 OMPRTL__kmpc_serialized_parallel,
565 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
566 // global_tid);
567 OMPRTL__kmpc_end_serialized_parallel,
568 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
569 // kmp_int32 num_threads);
570 OMPRTL__kmpc_push_num_threads,
571 // Call to void __kmpc_flush(ident_t *loc);
572 OMPRTL__kmpc_flush,
573 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
574 OMPRTL__kmpc_master,
575 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
576 OMPRTL__kmpc_end_master,
577 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
578 // int end_part);
579 OMPRTL__kmpc_omp_taskyield,
580 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
581 OMPRTL__kmpc_single,
582 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
583 OMPRTL__kmpc_end_single,
584 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
585 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
586 // kmp_routine_entry_t *task_entry);
587 OMPRTL__kmpc_omp_task_alloc,
588 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
589 // new_task);
590 OMPRTL__kmpc_omp_task,
591 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
592 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
593 // kmp_int32 didit);
594 OMPRTL__kmpc_copyprivate,
595 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
596 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
597 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
598 OMPRTL__kmpc_reduce,
599 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
600 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
601 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
602 // *lck);
603 OMPRTL__kmpc_reduce_nowait,
604 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
605 // kmp_critical_name *lck);
606 OMPRTL__kmpc_end_reduce,
607 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
608 // kmp_critical_name *lck);
609 OMPRTL__kmpc_end_reduce_nowait,
610 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
611 // kmp_task_t * new_task);
612 OMPRTL__kmpc_omp_task_begin_if0,
613 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
614 // kmp_task_t * new_task);
615 OMPRTL__kmpc_omp_task_complete_if0,
616 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
617 OMPRTL__kmpc_ordered,
618 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
619 OMPRTL__kmpc_end_ordered,
620 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
621 // global_tid);
622 OMPRTL__kmpc_omp_taskwait,
623 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
624 OMPRTL__kmpc_taskgroup,
625 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
626 OMPRTL__kmpc_end_taskgroup,
627 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
628 // int proc_bind);
629 OMPRTL__kmpc_push_proc_bind,
630 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
631 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
632 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
633 OMPRTL__kmpc_omp_task_with_deps,
634 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
635 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
636 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
637 OMPRTL__kmpc_omp_wait_deps,
638 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
639 // global_tid, kmp_int32 cncl_kind);
640 OMPRTL__kmpc_cancellationpoint,
641 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
642 // kmp_int32 cncl_kind);
643 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000644 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
645 // kmp_int32 num_teams, kmp_int32 thread_limit);
646 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000647 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
648 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000649 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000650 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
651 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
652 // sched, kmp_uint64 grainsize, void *task_dup);
653 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000654 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
655 // num_dims, struct kmp_dim *dims);
656 OMPRTL__kmpc_doacross_init,
657 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
658 OMPRTL__kmpc_doacross_fini,
659 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
660 // *vec);
661 OMPRTL__kmpc_doacross_post,
662 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
663 // *vec);
664 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000665 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
666 // *data);
667 OMPRTL__kmpc_task_reduction_init,
668 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
669 // *d);
670 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000671
672 //
673 // Offloading related calls
674 //
Alexey Bataev7bb33532019-01-07 21:30:43 +0000675 // Call to void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
676 // size);
677 OMPRTL__kmpc_push_target_tripcount,
George Rokos63bc9d62017-11-21 18:25:12 +0000678 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
679 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000680 // *arg_types);
681 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000682 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
683 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
684 // *arg_types);
685 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000686 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
687 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
688 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000689 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000690 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
691 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
692 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
693 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000694 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
695 OMPRTL__tgt_register_lib,
696 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
697 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000698 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
699 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000700 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000701 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
702 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
703 // *arg_types);
704 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000705 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
706 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000707 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000708 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
709 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
710 // *arg_types);
711 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000712 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
713 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000714 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000715 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
716 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
717 // *arg_types);
718 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000719};
720
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000721/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
722/// region.
723class CleanupTy final : public EHScopeStack::Cleanup {
724 PrePostActionTy *Action;
725
726public:
727 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
728 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
729 if (!CGF.HaveInsertPoint())
730 return;
731 Action->Exit(CGF);
732 }
733};
734
Hans Wennborg7eb54642015-09-10 17:07:54 +0000735} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000736
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000737void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
738 CodeGenFunction::RunCleanupsScope Scope(CGF);
739 if (PrePostAction) {
740 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
741 Callback(CodeGen, CGF, *PrePostAction);
742 } else {
743 PrePostActionTy Action;
744 Callback(CodeGen, CGF, Action);
745 }
746}
747
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000748/// Check if the combiner is a call to UDR combiner and if it is so return the
749/// UDR decl used for reduction.
750static const OMPDeclareReductionDecl *
751getReductionInit(const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000752 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
753 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
754 if (const auto *DRE =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000755 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000756 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000757 return DRD;
758 return nullptr;
759}
760
761static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
762 const OMPDeclareReductionDecl *DRD,
763 const Expr *InitOp,
764 Address Private, Address Original,
765 QualType Ty) {
766 if (DRD->getInitializer()) {
767 std::pair<llvm::Function *, llvm::Function *> Reduction =
768 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000769 const auto *CE = cast<CallExpr>(InitOp);
770 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000771 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
772 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000773 const auto *LHSDRE =
774 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
775 const auto *RHSDRE =
776 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000777 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
778 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000779 [=]() { return Private; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000780 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000781 [=]() { return Original; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000782 (void)PrivateScope.Privatize();
783 RValue Func = RValue::get(Reduction.second);
784 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
785 CGF.EmitIgnoredExpr(InitOp);
786 } else {
787 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
Alexey Bataev18fa2322018-05-02 14:20:50 +0000788 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000789 auto *GV = new llvm::GlobalVariable(
790 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
Alexey Bataev18fa2322018-05-02 14:20:50 +0000791 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000792 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
793 RValue InitRVal;
794 switch (CGF.getEvaluationKind(Ty)) {
795 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000796 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000797 break;
798 case TEK_Complex:
799 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000800 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000801 break;
802 case TEK_Aggregate:
803 InitRVal = RValue::getAggregate(LV.getAddress());
804 break;
805 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000806 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000807 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
808 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
809 /*IsInitializer=*/false);
810 }
811}
812
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000813/// Emit initialization of arrays of complex types.
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000814/// \param DestAddr Address of the array.
815/// \param Type Type of array.
816/// \param Init Initial expression of array.
817/// \param SrcAddr Address of the original array.
818static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000819 QualType Type, bool EmitDeclareReductionInit,
820 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000821 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000822 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000823 // Perform element-by-element initialization.
824 QualType ElementTy;
825
826 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000827 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
828 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000829 DestAddr =
830 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
831 if (DRD)
832 SrcAddr =
833 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
834
835 llvm::Value *SrcBegin = nullptr;
836 if (DRD)
837 SrcBegin = SrcAddr.getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000838 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000839 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000840 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000841 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000842 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
843 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
844 llvm::Value *IsEmpty =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000845 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
846 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
847
848 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000849 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000850 CGF.EmitBlock(BodyBB);
851
852 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
853
854 llvm::PHINode *SrcElementPHI = nullptr;
855 Address SrcElementCurrent = Address::invalid();
856 if (DRD) {
857 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
858 "omp.arraycpy.srcElementPast");
859 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
860 SrcElementCurrent =
861 Address(SrcElementPHI,
862 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
863 }
864 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
865 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
866 DestElementPHI->addIncoming(DestBegin, EntryBB);
867 Address DestElementCurrent =
868 Address(DestElementPHI,
869 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
870
871 // Emit copy.
872 {
873 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000874 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000875 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
876 SrcElementCurrent, ElementTy);
877 } else
878 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
879 /*IsInitializer=*/false);
880 }
881
882 if (DRD) {
883 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000884 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000885 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
886 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
887 }
888
889 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000890 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000891 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
892 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000893 llvm::Value *Done =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000894 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
895 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
896 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
897
898 // Done.
899 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
900}
901
902LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000903 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000904}
905
906LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
907 const Expr *E) {
908 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
909 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
910 return LValue();
911}
912
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000913void ReductionCodeGen::emitAggregateInitialization(
914 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
915 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000916 // Emit VarDecl with copy init for arrays.
917 // Get the address of the original variable captured in current
918 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000919 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000920 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000921 bool EmitDeclareReductionInit =
922 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000923 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000924 EmitDeclareReductionInit,
925 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
926 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000927 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000928}
929
930ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
931 ArrayRef<const Expr *> Privates,
932 ArrayRef<const Expr *> ReductionOps) {
933 ClausesData.reserve(Shareds.size());
934 SharedAddresses.reserve(Shareds.size());
935 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000936 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000937 auto IPriv = Privates.begin();
938 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000939 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 ClausesData.emplace_back(Ref, *IPriv, *IRed);
941 std::advance(IPriv, 1);
942 std::advance(IRed, 1);
943 }
944}
945
946void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
947 assert(SharedAddresses.size() == N &&
948 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000949 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
950 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
951 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000952}
953
954void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000955 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000956 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
957 QualType PrivateType = PrivateVD->getType();
958 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000959 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000960 Sizes.emplace_back(
961 CGF.getTypeSize(
962 SharedAddresses[N].first.getType().getNonReferenceType()),
963 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000964 return;
965 }
966 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000967 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000968 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000969 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
970 ->getElementType();
971 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000972 if (AsArraySection) {
973 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
974 SharedAddresses[N].first.getPointer());
975 Size = CGF.Builder.CreateNUWAdd(
976 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000977 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000978 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000979 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000980 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000981 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000982 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000983 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000984 CodeGenFunction::OpaqueValueMapping OpaqueMap(
985 CGF,
986 cast<OpaqueValueExpr>(
987 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
988 RValue::get(Size));
989 CGF.EmitVariablyModifiedType(PrivateType);
990}
991
992void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
993 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000994 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000995 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
996 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000997 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000998 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000999 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001000 "items.");
1001 return;
1002 }
1003 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1004 CGF,
1005 cast<OpaqueValueExpr>(
1006 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1007 RValue::get(Size));
1008 CGF.EmitVariablyModifiedType(PrivateType);
1009}
1010
1011void ReductionCodeGen::emitInitialization(
1012 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1013 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1014 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001015 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001016 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001017 const OMPDeclareReductionDecl *DRD =
1018 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001019 QualType PrivateType = PrivateVD->getType();
1020 PrivateAddr = CGF.Builder.CreateElementBitCast(
1021 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1022 QualType SharedType = SharedAddresses[N].first.getType();
1023 SharedLVal = CGF.MakeAddrLValue(
1024 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1025 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001026 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001027 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001028 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001029 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001030 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1031 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1032 PrivateAddr, SharedLVal.getAddress(),
1033 SharedLVal.getType());
1034 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1035 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1036 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1037 PrivateVD->getType().getQualifiers(),
1038 /*IsInitializer=*/false);
1039 }
1040}
1041
1042bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001043 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001044 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1045 QualType PrivateType = PrivateVD->getType();
1046 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1047 return DTorKind != QualType::DK_none;
1048}
1049
1050void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1051 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001052 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001053 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1054 QualType PrivateType = PrivateVD->getType();
1055 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1056 if (needCleanups(N)) {
1057 PrivateAddr = CGF.Builder.CreateElementBitCast(
1058 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1059 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1060 }
1061}
1062
1063static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1064 LValue BaseLV) {
1065 BaseTy = BaseTy.getNonReferenceType();
1066 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1067 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001068 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001069 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001070 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001071 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1072 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001073 }
1074 BaseTy = BaseTy->getPointeeType();
1075 }
1076 return CGF.MakeAddrLValue(
1077 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1078 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001079 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001080 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001081}
1082
1083static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1084 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1085 llvm::Value *Addr) {
1086 Address Tmp = Address::invalid();
1087 Address TopTmp = Address::invalid();
1088 Address MostTopTmp = Address::invalid();
1089 BaseTy = BaseTy.getNonReferenceType();
1090 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1091 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1092 Tmp = CGF.CreateMemTemp(BaseTy);
1093 if (TopTmp.isValid())
1094 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1095 else
1096 MostTopTmp = Tmp;
1097 TopTmp = Tmp;
1098 BaseTy = BaseTy->getPointeeType();
1099 }
1100 llvm::Type *Ty = BaseLVType;
1101 if (Tmp.isValid())
1102 Ty = Tmp.getElementType();
1103 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1104 if (Tmp.isValid()) {
1105 CGF.Builder.CreateStore(Addr, Tmp);
1106 return MostTopTmp;
1107 }
1108 return Address(Addr, BaseLVAlignment);
1109}
1110
Alexey Bataev1c44e152018-03-06 18:59:43 +00001111static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001112 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001113 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1114 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1115 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001117 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001118 Base = TempASE->getBase()->IgnoreParenImpCasts();
1119 DE = cast<DeclRefExpr>(Base);
1120 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001121 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1122 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1123 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001124 Base = TempASE->getBase()->IgnoreParenImpCasts();
1125 DE = cast<DeclRefExpr>(Base);
1126 OrigVD = cast<VarDecl>(DE->getDecl());
1127 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001128 return OrigVD;
1129}
1130
1131Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1132 Address PrivateAddr) {
1133 const DeclRefExpr *DE;
1134 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001136 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001137 LValue BaseLValue =
1138 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1139 OriginalBaseLValue);
1140 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1141 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001142 llvm::Value *PrivatePointer =
1143 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1144 PrivateAddr.getPointer(),
1145 SharedAddresses[N].first.getAddress().getType());
1146 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001147 return castToBase(CGF, OrigVD->getType(),
1148 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001149 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001150 OriginalBaseLValue.getAlignment(), Ptr);
1151 }
1152 BaseDecls.emplace_back(
1153 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1154 return PrivateAddr;
1155}
1156
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001157bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001158 const OMPDeclareReductionDecl *DRD =
1159 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001160 return DRD && DRD->getInitializer();
1161}
1162
Alexey Bataev18095712014-10-10 12:19:54 +00001163LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001164 return CGF.EmitLoadOfPointerLValue(
1165 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1166 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001167}
1168
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001169void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001170 if (!CGF.HaveInsertPoint())
1171 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001172 // 1.2.2 OpenMP Language Terminology
1173 // Structured block - An executable statement with a single entry at the
1174 // top and a single exit at the bottom.
1175 // The point of exit cannot be a branch out of the structured block.
1176 // longjmp() and throw() must not violate the entry/exit criteria.
1177 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001178 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001179 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001180}
1181
Alexey Bataev62b63b12015-03-10 07:28:44 +00001182LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1183 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001184 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1185 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001186 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001187}
1188
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001189static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1190 QualType FieldTy) {
1191 auto *Field = FieldDecl::Create(
1192 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1193 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1194 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1195 Field->setAccess(AS_public);
1196 DC->addDecl(Field);
1197 return Field;
1198}
1199
Alexey Bataev18fa2322018-05-02 14:20:50 +00001200CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1201 StringRef Separator)
1202 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1203 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001204 ASTContext &C = CGM.getContext();
1205 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1206 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1207 RD->startDefinition();
1208 // reserved_1
1209 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1210 // flags
1211 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1212 // reserved_2
1213 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1214 // reserved_3
1215 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1216 // psource
1217 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1218 RD->completeDefinition();
1219 IdentQTy = C.getRecordType(RD);
1220 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001221 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001222
1223 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001224}
1225
Alexey Bataev91797552015-03-18 04:13:55 +00001226void CGOpenMPRuntime::clear() {
1227 InternalVars.clear();
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00001228 // Clean non-target variable declarations possibly used only in debug info.
1229 for (const auto &Data : EmittedNonTargetVariables) {
1230 if (!Data.getValue().pointsToAliveValue())
1231 continue;
1232 auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
1233 if (!GV)
1234 continue;
1235 if (!GV->isDeclaration() || GV->getNumUses() > 0)
1236 continue;
1237 GV->eraseFromParent();
1238 }
Alexey Bataev91797552015-03-18 04:13:55 +00001239}
1240
Alexey Bataev18fa2322018-05-02 14:20:50 +00001241std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1242 SmallString<128> Buffer;
1243 llvm::raw_svector_ostream OS(Buffer);
1244 StringRef Sep = FirstSeparator;
1245 for (StringRef Part : Parts) {
1246 OS << Sep << Part;
1247 Sep = Separator;
1248 }
1249 return OS.str();
1250}
1251
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001252static llvm::Function *
1253emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1254 const Expr *CombinerInitializer, const VarDecl *In,
1255 const VarDecl *Out, bool IsCombiner) {
1256 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001257 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001258 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1259 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001260 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001261 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001262 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001263 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001264 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001265 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001266 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001267 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001268 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001269 std::string Name = CGM.getOpenMPRuntime().getName(
1270 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1271 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1272 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001273 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001274 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001275 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001276 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001277 CodeGenFunction CGF(CGM);
1278 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1279 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001280 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1281 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001282 CodeGenFunction::OMPPrivateScope Scope(CGF);
1283 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001284 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001285 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1286 .getAddress();
1287 });
1288 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001289 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001290 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1291 .getAddress();
1292 });
1293 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001294 if (!IsCombiner && Out->hasInit() &&
1295 !CGF.isTrivialInitializer(Out->getInit())) {
1296 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1297 Out->getType().getQualifiers(),
1298 /*IsInitializer=*/true);
1299 }
1300 if (CombinerInitializer)
1301 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001302 Scope.ForceCleanup();
1303 CGF.FinishFunction();
1304 return Fn;
1305}
1306
1307void CGOpenMPRuntime::emitUserDefinedReduction(
1308 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1309 if (UDRMap.count(D) > 0)
1310 return;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001311 llvm::Function *Combiner = emitCombinerOrInitializer(
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001312 CGM, D->getType(), D->getCombiner(),
1313 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1314 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001315 /*IsCombiner=*/true);
1316 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001317 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001318 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001319 CGM, D->getType(),
1320 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1321 : nullptr,
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001322 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1323 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001324 /*IsCombiner=*/false);
1325 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001326 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001327 if (CGF) {
1328 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1329 Decls.second.push_back(D);
1330 }
1331}
1332
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001333std::pair<llvm::Function *, llvm::Function *>
1334CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1335 auto I = UDRMap.find(D);
1336 if (I != UDRMap.end())
1337 return I->second;
1338 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1339 return UDRMap.lookup(D);
1340}
1341
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001342static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1343 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1344 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1345 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001346 assert(ThreadIDVar->getType()->isPointerType() &&
1347 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001348 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001349 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001350 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001351 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001352 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001353 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001354 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001355 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001356 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001357 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001358 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001359 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001360 else if (const auto *OPFD =
1361 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001362 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001363 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001364 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1365 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001366 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001367 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001368 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001369 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001370}
1371
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001372llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1373 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1374 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1375 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1376 return emitParallelOrTeamsOutlinedFunction(
1377 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1378}
1379
1380llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1381 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1382 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1383 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1384 return emitParallelOrTeamsOutlinedFunction(
1385 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1386}
1387
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001388llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1389 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001390 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1391 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1392 bool Tied, unsigned &NumberOfParts) {
1393 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1394 PrePostActionTy &) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001395 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1396 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001397 llvm::Value *TaskArgs[] = {
1398 UpLoc, ThreadID,
1399 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1400 TaskTVar->getType()->castAs<PointerType>())
1401 .getPointer()};
1402 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1403 };
1404 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1405 UntiedCodeGen);
1406 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001407 assert(!ThreadIDVar->getType()->isPointerType() &&
1408 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001409 const OpenMPDirectiveKind Region =
1410 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1411 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001412 const CapturedStmt *CS = D.getCapturedStmt(Region);
1413 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001414 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001415 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1416 InnermostKind,
1417 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001418 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001419 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001420 if (!Tied)
1421 NumberOfParts = Action.getNumberOfParts();
1422 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001423}
1424
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001425static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1426 const RecordDecl *RD, const CGRecordLayout &RL,
1427 ArrayRef<llvm::Constant *> Data) {
1428 llvm::StructType *StructTy = RL.getLLVMType();
1429 unsigned PrevIdx = 0;
1430 ConstantInitBuilder CIBuilder(CGM);
1431 auto DI = Data.begin();
1432 for (const FieldDecl *FD : RD->fields()) {
1433 unsigned Idx = RL.getLLVMFieldNo(FD);
1434 // Fill the alignment.
1435 for (unsigned I = PrevIdx; I < Idx; ++I)
1436 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1437 PrevIdx = Idx + 1;
1438 Fields.add(*DI);
1439 ++DI;
1440 }
1441}
1442
1443template <class... As>
1444static llvm::GlobalVariable *
Mike Ricee1ca7b62018-08-29 15:45:11 +00001445createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
1446 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1447 As &&... Args) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001448 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1449 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1450 ConstantInitBuilder CIBuilder(CGM);
1451 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1452 buildStructValue(Fields, CGM, RD, RL, Data);
1453 return Fields.finishAndCreateGlobal(
Mike Ricee1ca7b62018-08-29 15:45:11 +00001454 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
1455 std::forward<As>(Args)...);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001456}
1457
1458template <typename T>
Benjamin Kramer651d0bf2018-05-15 21:26:47 +00001459static void
1460createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1461 ArrayRef<llvm::Constant *> Data,
1462 T &Parent) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001463 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1464 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1465 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1466 buildStructValue(Fields, CGM, RD, RL, Data);
1467 Fields.finishAndAddTo(Parent);
1468}
1469
Alexey Bataev50b3c952016-02-19 10:38:26 +00001470Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001471 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataevceeaa482018-11-21 21:04:34 +00001472 unsigned Reserved2Flags = getDefaultLocationReserved2Flags();
1473 FlagsTy FlagsKey(Flags, Reserved2Flags);
1474 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(FlagsKey);
Alexey Bataev9959db52014-05-06 10:08:46 +00001475 if (!Entry) {
1476 if (!DefaultOpenMPPSource) {
1477 // Initialize default location for psource field of ident_t structure of
1478 // all ident_t objects. Format is ";file;function;line;column;;".
1479 // Taken from
1480 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1481 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001482 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001483 DefaultOpenMPPSource =
1484 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1485 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001486
Alexey Bataevceeaa482018-11-21 21:04:34 +00001487 llvm::Constant *Data[] = {
1488 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1489 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1490 llvm::ConstantInt::get(CGM.Int32Ty, Reserved2Flags),
1491 llvm::ConstantInt::getNullValue(CGM.Int32Ty), DefaultOpenMPPSource};
Mike Ricee1ca7b62018-08-29 15:45:11 +00001492 llvm::GlobalValue *DefaultOpenMPLocation =
Alexey Bataevceeaa482018-11-21 21:04:34 +00001493 createGlobalStruct(CGM, IdentQTy, isDefaultLocationConstant(), Data, "",
Mike Ricee1ca7b62018-08-29 15:45:11 +00001494 llvm::GlobalValue::PrivateLinkage);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001495 DefaultOpenMPLocation->setUnnamedAddr(
1496 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001497
Alexey Bataevceeaa482018-11-21 21:04:34 +00001498 OpenMPDefaultLocMap[FlagsKey] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001499 }
John McCall7f416cc2015-09-08 08:05:57 +00001500 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001501}
1502
Alexey Bataevfd006c42018-10-05 15:08:53 +00001503void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
1504 bool AtCurrentPoint) {
1505 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1506 assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
1507
1508 llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1509 if (AtCurrentPoint) {
1510 Elem.second.ServiceInsertPt = new llvm::BitCastInst(
1511 Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
1512 } else {
1513 Elem.second.ServiceInsertPt =
1514 new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1515 Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
1516 }
1517}
1518
1519void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
1520 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1521 if (Elem.second.ServiceInsertPt) {
1522 llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
1523 Elem.second.ServiceInsertPt = nullptr;
1524 Ptr->eraseFromParent();
1525 }
1526}
1527
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001528llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1529 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001530 unsigned Flags) {
1531 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001532 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001533 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001534 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001535 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001536
1537 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1538
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001539 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001540 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001541 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1542 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001543 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001544
Alexander Musmanc6388682014-12-15 07:07:06 +00001545 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1546 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001547 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001548 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001549 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001550 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001551 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001552 LocValue = AI;
1553
Alexey Bataevfd006c42018-10-05 15:08:53 +00001554 if (!Elem.second.ServiceInsertPt)
1555 setLocThreadIdInsertPt(CGF);
Alexey Bataev9959db52014-05-06 10:08:46 +00001556 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001557 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001558 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001559 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001560 }
1561
1562 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001563 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1564 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1565 LValue PSource =
1566 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001567
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001568 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001569 if (OMPDebugLoc == nullptr) {
1570 SmallString<128> Buffer2;
1571 llvm::raw_svector_ostream OS2(Buffer2);
1572 // Build debug location
1573 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1574 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001575 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001576 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001577 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1578 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1579 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001580 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001581 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001582 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001583
John McCall7f416cc2015-09-08 08:05:57 +00001584 // Our callers always pass this to a runtime function, so for
1585 // convenience, go ahead and return a naked pointer.
1586 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001587}
1588
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001589llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1590 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001591 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1592
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001593 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001594 // Check whether we've already cached a load of the thread id in this
1595 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001596 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001597 if (I != OpenMPLocThreadIDMap.end()) {
1598 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001599 if (ThreadID != nullptr)
1600 return ThreadID;
1601 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001602 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001603 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1604 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001605 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001606 if (auto *OMPRegionInfo =
1607 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1608 if (OMPRegionInfo->getThreadIDVariable()) {
1609 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001610 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001611 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001612 // If value loaded in entry block, cache it and use it everywhere in
1613 // function.
1614 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1615 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1616 Elem.second.ThreadID = ThreadID;
1617 }
1618 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001619 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001620 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001621 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001622
1623 // This is not an outlined function region - need to call __kmpc_int32
1624 // kmpc_global_thread_num(ident_t *loc).
1625 // Generate thread id value and cache this value for use across the
1626 // function.
Alexey Bataevfd006c42018-10-05 15:08:53 +00001627 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1628 if (!Elem.second.ServiceInsertPt)
1629 setLocThreadIdInsertPt(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001630 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001631 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001632 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001633 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1634 emitUpdateLocation(CGF, Loc));
1635 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001636 Elem.second.ThreadID = Call;
1637 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001638}
1639
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001640void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001641 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataevfd006c42018-10-05 15:08:53 +00001642 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1643 clearLocThreadIdInsertPt(CGF);
Alexey Bataev03b340a2014-10-21 03:16:40 +00001644 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001645 }
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001646 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001647 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001648 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001649 FunctionUDRMap.erase(CGF.CurFn);
1650 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001651}
1652
1653llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001654 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001655}
1656
1657llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001658 if (!Kmpc_MicroTy) {
1659 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1660 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1661 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1662 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1663 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001664 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1665}
1666
1667llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001668CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001669 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001670 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001671 case OMPRTL__kmpc_fork_call: {
1672 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1673 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001674 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1675 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001676 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001677 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001678 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
Johannes Doerfertac991bb2019-01-19 05:36:54 +00001679 if (auto *F = dyn_cast<llvm::Function>(RTLFn)) {
1680 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
1681 llvm::LLVMContext &Ctx = F->getContext();
1682 llvm::MDBuilder MDB(Ctx);
1683 // Annotate the callback behavior of the __kmpc_fork_call:
1684 // - The callback callee is argument number 2 (microtask).
1685 // - The first two arguments of the callback callee are unknown (-1).
1686 // - All variadic arguments to the __kmpc_fork_call are passed to the
1687 // callback callee.
1688 F->addMetadata(
1689 llvm::LLVMContext::MD_callback,
1690 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1691 2, {-1, -1},
1692 /* VarArgsArePassed */ true)}));
1693 }
1694 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001695 break;
1696 }
1697 case OMPRTL__kmpc_global_thread_num: {
1698 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001699 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001700 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001701 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001702 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1703 break;
1704 }
Alexey Bataev97720002014-11-11 04:05:39 +00001705 case OMPRTL__kmpc_threadprivate_cached: {
1706 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1707 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1708 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1709 CGM.VoidPtrTy, CGM.SizeTy,
1710 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001711 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001712 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1713 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1714 break;
1715 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001716 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001717 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1718 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001719 llvm::Type *TypeParams[] = {
1720 getIdentTyPointerTy(), CGM.Int32Ty,
1721 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001722 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001723 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1724 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1725 break;
1726 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001727 case OMPRTL__kmpc_critical_with_hint: {
1728 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1729 // kmp_critical_name *crit, uintptr_t hint);
1730 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1731 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1732 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001733 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001734 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1735 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1736 break;
1737 }
Alexey Bataev97720002014-11-11 04:05:39 +00001738 case OMPRTL__kmpc_threadprivate_register: {
1739 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1740 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1741 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001742 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001743 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1744 /*isVarArg*/ false)->getPointerTo();
1745 // typedef void *(*kmpc_cctor)(void *, void *);
1746 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001747 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001748 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001749 /*isVarArg*/ false)
1750 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001751 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001752 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001753 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1754 ->getPointerTo();
1755 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1756 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001757 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001758 /*isVarArg*/ false);
1759 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1760 break;
1761 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001762 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001763 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1764 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001765 llvm::Type *TypeParams[] = {
1766 getIdentTyPointerTy(), CGM.Int32Ty,
1767 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001768 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001769 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1770 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1771 break;
1772 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001773 case OMPRTL__kmpc_cancel_barrier: {
1774 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1775 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001776 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001777 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001778 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1779 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001780 break;
1781 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001782 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001783 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001784 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001785 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001786 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1787 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1788 break;
1789 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001790 case OMPRTL__kmpc_for_static_fini: {
1791 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1792 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001793 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001794 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1795 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1796 break;
1797 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001798 case OMPRTL__kmpc_push_num_threads: {
1799 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1800 // kmp_int32 num_threads)
1801 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1802 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001803 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001804 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1805 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1806 break;
1807 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001808 case OMPRTL__kmpc_serialized_parallel: {
1809 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1810 // global_tid);
1811 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001812 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001813 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1814 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1815 break;
1816 }
1817 case OMPRTL__kmpc_end_serialized_parallel: {
1818 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1819 // global_tid);
1820 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001821 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001822 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1823 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1824 break;
1825 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001826 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001827 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001828 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001829 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001830 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001831 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1832 break;
1833 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001834 case OMPRTL__kmpc_master: {
1835 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1836 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001837 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001838 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1839 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1840 break;
1841 }
1842 case OMPRTL__kmpc_end_master: {
1843 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1844 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001845 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001846 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1847 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1848 break;
1849 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001850 case OMPRTL__kmpc_omp_taskyield: {
1851 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1852 // int end_part);
1853 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001854 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001855 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1856 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1857 break;
1858 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001859 case OMPRTL__kmpc_single: {
1860 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1861 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001862 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001863 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1864 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1865 break;
1866 }
1867 case OMPRTL__kmpc_end_single: {
1868 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1869 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001870 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001871 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1872 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1873 break;
1874 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001875 case OMPRTL__kmpc_omp_task_alloc: {
1876 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1877 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1878 // kmp_routine_entry_t *task_entry);
1879 assert(KmpRoutineEntryPtrTy != nullptr &&
1880 "Type kmp_routine_entry_t must be created.");
1881 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1882 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1883 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001884 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001885 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1886 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1887 break;
1888 }
1889 case OMPRTL__kmpc_omp_task: {
1890 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1891 // *new_task);
1892 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1893 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001894 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001895 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1896 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1897 break;
1898 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001899 case OMPRTL__kmpc_copyprivate: {
1900 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001901 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001902 // kmp_int32 didit);
1903 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1904 auto *CpyFnTy =
1905 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001906 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001907 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1908 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001909 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001910 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1911 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1912 break;
1913 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001914 case OMPRTL__kmpc_reduce: {
1915 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1916 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1917 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1918 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1919 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1920 /*isVarArg=*/false);
1921 llvm::Type *TypeParams[] = {
1922 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1923 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1924 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001925 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001926 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1927 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1928 break;
1929 }
1930 case OMPRTL__kmpc_reduce_nowait: {
1931 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1932 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1933 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1934 // *lck);
1935 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1936 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1937 /*isVarArg=*/false);
1938 llvm::Type *TypeParams[] = {
1939 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1940 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1941 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001942 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001943 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1944 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1945 break;
1946 }
1947 case OMPRTL__kmpc_end_reduce: {
1948 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1949 // kmp_critical_name *lck);
1950 llvm::Type *TypeParams[] = {
1951 getIdentTyPointerTy(), CGM.Int32Ty,
1952 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001953 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001954 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1955 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1956 break;
1957 }
1958 case OMPRTL__kmpc_end_reduce_nowait: {
1959 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1960 // kmp_critical_name *lck);
1961 llvm::Type *TypeParams[] = {
1962 getIdentTyPointerTy(), CGM.Int32Ty,
1963 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001964 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001965 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1966 RTLFn =
1967 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1968 break;
1969 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001970 case OMPRTL__kmpc_omp_task_begin_if0: {
1971 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1972 // *new_task);
1973 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1974 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001975 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001976 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1977 RTLFn =
1978 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1979 break;
1980 }
1981 case OMPRTL__kmpc_omp_task_complete_if0: {
1982 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1983 // *new_task);
1984 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1985 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001986 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001987 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1988 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1989 /*Name=*/"__kmpc_omp_task_complete_if0");
1990 break;
1991 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001992 case OMPRTL__kmpc_ordered: {
1993 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1994 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001995 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001996 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1997 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1998 break;
1999 }
2000 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002001 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002002 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002003 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002004 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2005 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
2006 break;
2007 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002008 case OMPRTL__kmpc_omp_taskwait: {
2009 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
2010 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002011 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002012 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2013 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
2014 break;
2015 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002016 case OMPRTL__kmpc_taskgroup: {
2017 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
2018 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002019 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002020 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2021 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
2022 break;
2023 }
2024 case OMPRTL__kmpc_end_taskgroup: {
2025 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
2026 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002027 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002028 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2029 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
2030 break;
2031 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00002032 case OMPRTL__kmpc_push_proc_bind: {
2033 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
2034 // int proc_bind)
2035 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002036 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002037 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2038 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2039 break;
2040 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002041 case OMPRTL__kmpc_omp_task_with_deps: {
2042 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2043 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2044 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2045 llvm::Type *TypeParams[] = {
2046 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2047 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002048 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002049 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2050 RTLFn =
2051 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2052 break;
2053 }
2054 case OMPRTL__kmpc_omp_wait_deps: {
2055 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2056 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2057 // kmp_depend_info_t *noalias_dep_list);
2058 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2059 CGM.Int32Ty, CGM.VoidPtrTy,
2060 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002061 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002062 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2063 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2064 break;
2065 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002066 case OMPRTL__kmpc_cancellationpoint: {
2067 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2068 // global_tid, kmp_int32 cncl_kind)
2069 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002070 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002071 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2072 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2073 break;
2074 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002075 case OMPRTL__kmpc_cancel: {
2076 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2077 // kmp_int32 cncl_kind)
2078 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002079 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002080 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2081 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2082 break;
2083 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002084 case OMPRTL__kmpc_push_num_teams: {
2085 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2086 // kmp_int32 num_teams, kmp_int32 num_threads)
2087 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2088 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002089 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002090 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2091 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2092 break;
2093 }
2094 case OMPRTL__kmpc_fork_teams: {
2095 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2096 // microtask, ...);
2097 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2098 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002099 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002100 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2101 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002102 if (auto *F = dyn_cast<llvm::Function>(RTLFn)) {
2103 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
2104 llvm::LLVMContext &Ctx = F->getContext();
2105 llvm::MDBuilder MDB(Ctx);
2106 // Annotate the callback behavior of the __kmpc_fork_teams:
2107 // - The callback callee is argument number 2 (microtask).
2108 // - The first two arguments of the callback callee are unknown (-1).
2109 // - All variadic arguments to the __kmpc_fork_teams are passed to the
2110 // callback callee.
2111 F->addMetadata(
2112 llvm::LLVMContext::MD_callback,
2113 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2114 2, {-1, -1},
2115 /* VarArgsArePassed */ true)}));
2116 }
2117 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002118 break;
2119 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002120 case OMPRTL__kmpc_taskloop: {
2121 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2122 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2123 // sched, kmp_uint64 grainsize, void *task_dup);
2124 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2125 CGM.IntTy,
2126 CGM.VoidPtrTy,
2127 CGM.IntTy,
2128 CGM.Int64Ty->getPointerTo(),
2129 CGM.Int64Ty->getPointerTo(),
2130 CGM.Int64Ty,
2131 CGM.IntTy,
2132 CGM.IntTy,
2133 CGM.Int64Ty,
2134 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002135 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002136 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2137 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2138 break;
2139 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002140 case OMPRTL__kmpc_doacross_init: {
2141 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2142 // num_dims, struct kmp_dim *dims);
2143 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2144 CGM.Int32Ty,
2145 CGM.Int32Ty,
2146 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002147 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002148 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2149 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2150 break;
2151 }
2152 case OMPRTL__kmpc_doacross_fini: {
2153 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2154 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002155 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002156 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2157 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2158 break;
2159 }
2160 case OMPRTL__kmpc_doacross_post: {
2161 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2162 // *vec);
2163 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2164 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002165 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002166 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2167 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2168 break;
2169 }
2170 case OMPRTL__kmpc_doacross_wait: {
2171 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2172 // *vec);
2173 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2174 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002175 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002176 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2177 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2178 break;
2179 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002180 case OMPRTL__kmpc_task_reduction_init: {
2181 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2182 // *data);
2183 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002184 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002185 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2186 RTLFn =
2187 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2188 break;
2189 }
2190 case OMPRTL__kmpc_task_reduction_get_th_data: {
2191 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2192 // *d);
2193 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002194 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002195 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2196 RTLFn = CGM.CreateRuntimeFunction(
2197 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2198 break;
2199 }
Alexey Bataev7bb33532019-01-07 21:30:43 +00002200 case OMPRTL__kmpc_push_target_tripcount: {
2201 // Build void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
2202 // size);
2203 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int64Ty};
2204 llvm::FunctionType *FnTy =
2205 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2206 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_target_tripcount");
2207 break;
2208 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002209 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002210 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2211 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002212 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002213 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002214 CGM.VoidPtrTy,
2215 CGM.Int32Ty,
2216 CGM.VoidPtrPtrTy,
2217 CGM.VoidPtrPtrTy,
2218 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002219 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002220 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002221 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2222 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2223 break;
2224 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002225 case OMPRTL__tgt_target_nowait: {
2226 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2227 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2228 // int64_t *arg_types);
2229 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2230 CGM.VoidPtrTy,
2231 CGM.Int32Ty,
2232 CGM.VoidPtrPtrTy,
2233 CGM.VoidPtrPtrTy,
2234 CGM.SizeTy->getPointerTo(),
2235 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002236 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002237 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2238 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2239 break;
2240 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002241 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002242 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002243 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002244 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2245 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002246 CGM.VoidPtrTy,
2247 CGM.Int32Ty,
2248 CGM.VoidPtrPtrTy,
2249 CGM.VoidPtrPtrTy,
2250 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002251 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002252 CGM.Int32Ty,
2253 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002254 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002255 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2256 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2257 break;
2258 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002259 case OMPRTL__tgt_target_teams_nowait: {
2260 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2261 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2262 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2263 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2264 CGM.VoidPtrTy,
2265 CGM.Int32Ty,
2266 CGM.VoidPtrPtrTy,
2267 CGM.VoidPtrPtrTy,
2268 CGM.SizeTy->getPointerTo(),
2269 CGM.Int64Ty->getPointerTo(),
2270 CGM.Int32Ty,
2271 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002272 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002273 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2274 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2275 break;
2276 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002277 case OMPRTL__tgt_register_lib: {
2278 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2279 QualType ParamTy =
2280 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2281 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002282 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002283 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2284 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2285 break;
2286 }
2287 case OMPRTL__tgt_unregister_lib: {
2288 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2289 QualType ParamTy =
2290 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2291 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002292 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002293 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2294 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2295 break;
2296 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002297 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002298 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2299 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2300 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002301 CGM.Int32Ty,
2302 CGM.VoidPtrPtrTy,
2303 CGM.VoidPtrPtrTy,
2304 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002305 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002306 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002307 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2308 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2309 break;
2310 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002311 case OMPRTL__tgt_target_data_begin_nowait: {
2312 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2313 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2314 // *arg_types);
2315 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2316 CGM.Int32Ty,
2317 CGM.VoidPtrPtrTy,
2318 CGM.VoidPtrPtrTy,
2319 CGM.SizeTy->getPointerTo(),
2320 CGM.Int64Ty->getPointerTo()};
2321 auto *FnTy =
2322 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2323 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2324 break;
2325 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002326 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002327 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2328 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2329 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002330 CGM.Int32Ty,
2331 CGM.VoidPtrPtrTy,
2332 CGM.VoidPtrPtrTy,
2333 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002334 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002335 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002336 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2337 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2338 break;
2339 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002340 case OMPRTL__tgt_target_data_end_nowait: {
2341 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2342 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2343 // *arg_types);
2344 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2345 CGM.Int32Ty,
2346 CGM.VoidPtrPtrTy,
2347 CGM.VoidPtrPtrTy,
2348 CGM.SizeTy->getPointerTo(),
2349 CGM.Int64Ty->getPointerTo()};
2350 auto *FnTy =
2351 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2352 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2353 break;
2354 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002355 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002356 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2357 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2358 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002359 CGM.Int32Ty,
2360 CGM.VoidPtrPtrTy,
2361 CGM.VoidPtrPtrTy,
2362 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002363 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002364 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002365 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2366 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2367 break;
2368 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002369 case OMPRTL__tgt_target_data_update_nowait: {
2370 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2371 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2372 // *arg_types);
2373 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2374 CGM.Int32Ty,
2375 CGM.VoidPtrPtrTy,
2376 CGM.VoidPtrPtrTy,
2377 CGM.SizeTy->getPointerTo(),
2378 CGM.Int64Ty->getPointerTo()};
2379 auto *FnTy =
2380 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2381 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2382 break;
2383 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002384 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002385 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002386 return RTLFn;
2387}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002388
Alexander Musman21212e42015-03-13 10:38:23 +00002389llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2390 bool IVSigned) {
2391 assert((IVSize == 32 || IVSize == 64) &&
2392 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002393 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2394 : "__kmpc_for_static_init_4u")
2395 : (IVSigned ? "__kmpc_for_static_init_8"
2396 : "__kmpc_for_static_init_8u");
2397 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2398 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002399 llvm::Type *TypeParams[] = {
2400 getIdentTyPointerTy(), // loc
2401 CGM.Int32Ty, // tid
2402 CGM.Int32Ty, // schedtype
2403 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2404 PtrTy, // p_lower
2405 PtrTy, // p_upper
2406 PtrTy, // p_stride
2407 ITy, // incr
2408 ITy // chunk
2409 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002410 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002411 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2412 return CGM.CreateRuntimeFunction(FnTy, Name);
2413}
2414
Alexander Musman92bdaab2015-03-12 13:37:50 +00002415llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2416 bool IVSigned) {
2417 assert((IVSize == 32 || IVSize == 64) &&
2418 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002419 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002420 IVSize == 32
2421 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2422 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002423 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002424 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2425 CGM.Int32Ty, // tid
2426 CGM.Int32Ty, // schedtype
2427 ITy, // lower
2428 ITy, // upper
2429 ITy, // stride
2430 ITy // chunk
2431 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002432 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002433 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2434 return CGM.CreateRuntimeFunction(FnTy, Name);
2435}
2436
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002437llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2438 bool IVSigned) {
2439 assert((IVSize == 32 || IVSize == 64) &&
2440 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002441 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002442 IVSize == 32
2443 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2444 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2445 llvm::Type *TypeParams[] = {
2446 getIdentTyPointerTy(), // loc
2447 CGM.Int32Ty, // tid
2448 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002449 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002450 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2451 return CGM.CreateRuntimeFunction(FnTy, Name);
2452}
2453
Alexander Musman92bdaab2015-03-12 13:37:50 +00002454llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2455 bool IVSigned) {
2456 assert((IVSize == 32 || IVSize == 64) &&
2457 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002458 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002459 IVSize == 32
2460 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2461 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002462 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2463 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002464 llvm::Type *TypeParams[] = {
2465 getIdentTyPointerTy(), // loc
2466 CGM.Int32Ty, // tid
2467 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2468 PtrTy, // p_lower
2469 PtrTy, // p_upper
2470 PtrTy // p_stride
2471 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002472 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002473 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2474 return CGM.CreateRuntimeFunction(FnTy, Name);
2475}
2476
Alexey Bataev03f270c2018-03-30 18:31:07 +00002477Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2478 if (CGM.getLangOpts().OpenMPSimd)
2479 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002480 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002481 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002482 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2483 SmallString<64> PtrName;
2484 {
2485 llvm::raw_svector_ostream OS(PtrName);
2486 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2487 }
2488 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2489 if (!Ptr) {
2490 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2491 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2492 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002493 if (!CGM.getLangOpts().OpenMPIsDevice) {
2494 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2495 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2496 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2497 }
2498 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2499 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002500 }
2501 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2502 }
2503 return Address::invalid();
2504}
2505
Alexey Bataev97720002014-11-11 04:05:39 +00002506llvm::Constant *
2507CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002508 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2509 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002510 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002511 std::string Suffix = getName({"cache", ""});
2512 return getOrCreateInternalVariable(
2513 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002514}
2515
John McCall7f416cc2015-09-08 08:05:57 +00002516Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2517 const VarDecl *VD,
2518 Address VDAddr,
2519 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002520 if (CGM.getLangOpts().OpenMPUseTLS &&
2521 CGM.getContext().getTargetInfo().isTLSSupported())
2522 return VDAddr;
2523
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002524 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002525 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002526 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2527 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002528 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2529 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002530 return Address(CGF.EmitRuntimeCall(
2531 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2532 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002533}
2534
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002535void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002536 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002537 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2538 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2539 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002540 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002541 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002542 OMPLoc);
2543 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2544 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002545 llvm::Value *Args[] = {
2546 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2547 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002548 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002549 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002550}
2551
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002552llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002553 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002554 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002555 if (CGM.getLangOpts().OpenMPUseTLS &&
2556 CGM.getContext().getTargetInfo().isTLSSupported())
2557 return nullptr;
2558
Alexey Bataev97720002014-11-11 04:05:39 +00002559 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002560 if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
Alexey Bataev97720002014-11-11 04:05:39 +00002561 QualType ASTTy = VD->getType();
2562
2563 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002564 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002565 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2566 // Generate function that re-emits the declaration's initializer into the
2567 // threadprivate copy of the variable VD
2568 CodeGenFunction CtorCGF(CGM);
2569 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002570 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2571 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002572 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002573 Args.push_back(&Dst);
2574
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002575 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002576 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002577 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002578 std::string Name = getName({"__kmpc_global_ctor_", ""});
2579 llvm::Function *Fn =
2580 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002581 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002582 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002583 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002584 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002585 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002586 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002587 Arg = CtorCGF.Builder.CreateElementBitCast(
2588 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002589 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2590 /*IsInitializer=*/true);
2591 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002592 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002593 CGM.getContext().VoidPtrTy, Dst.getLocation());
2594 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2595 CtorCGF.FinishFunction();
2596 Ctor = Fn;
2597 }
2598 if (VD->getType().isDestructedType() != QualType::DK_none) {
2599 // Generate function that emits destructor call for the threadprivate copy
2600 // of the variable VD
2601 CodeGenFunction DtorCGF(CGM);
2602 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002603 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2604 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002605 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002606 Args.push_back(&Dst);
2607
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002608 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002609 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002610 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002611 std::string Name = getName({"__kmpc_global_dtor_", ""});
2612 llvm::Function *Fn =
2613 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002614 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002615 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002616 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002617 // Create a scope with an artificial location for the body of this function.
2618 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002619 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002620 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002621 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2622 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002623 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2624 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2625 DtorCGF.FinishFunction();
2626 Dtor = Fn;
2627 }
2628 // Do not emit init function if it is not required.
2629 if (!Ctor && !Dtor)
2630 return nullptr;
2631
2632 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002633 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2634 /*isVarArg=*/false)
2635 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002636 // Copying constructor for the threadprivate variable.
2637 // Must be NULL - reserved by runtime, but currently it requires that this
2638 // parameter is always NULL. Otherwise it fires assertion.
2639 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2640 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002641 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2642 /*isVarArg=*/false)
2643 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002644 Ctor = llvm::Constant::getNullValue(CtorTy);
2645 }
2646 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002647 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2648 /*isVarArg=*/false)
2649 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002650 Dtor = llvm::Constant::getNullValue(DtorTy);
2651 }
2652 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002653 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002654 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002655 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002656 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002657 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002658 CodeGenFunction InitCGF(CGM);
2659 FunctionArgList ArgList;
2660 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2661 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002662 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002663 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002664 InitCGF.FinishFunction();
2665 return InitFunction;
2666 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002667 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002668 }
2669 return nullptr;
2670}
2671
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002672/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002673/// consists of the file and device IDs as well as line number associated with
2674/// the relevant entry source location.
2675static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2676 unsigned &DeviceID, unsigned &FileID,
2677 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002678 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002679
2680 // The loc should be always valid and have a file ID (the user cannot use
2681 // #pragma directives in macros)
2682
2683 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002684
2685 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2686 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2687
2688 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002689 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2690 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2691 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002692
2693 DeviceID = ID.getDevice();
2694 FileID = ID.getFile();
2695 LineNum = PLoc.getLine();
2696}
2697
2698bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2699 llvm::GlobalVariable *Addr,
2700 bool PerformInit) {
2701 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002702 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002703 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
Alexey Bataevd01b7492018-08-15 19:45:12 +00002704 return CGM.getLangOpts().OpenMPIsDevice;
Alexey Bataev34f8a702018-03-28 14:28:54 +00002705 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002706 if (VD && !DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
Alexey Bataev34f8a702018-03-28 14:28:54 +00002707 return CGM.getLangOpts().OpenMPIsDevice;
2708
2709 QualType ASTTy = VD->getType();
2710
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002711 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002712 // Produce the unique prefix to identify the new target regions. We use
2713 // the source location of the variable declaration which we know to not
2714 // conflict with any target region.
2715 unsigned DeviceID;
2716 unsigned FileID;
2717 unsigned Line;
2718 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2719 SmallString<128> Buffer, Out;
2720 {
2721 llvm::raw_svector_ostream OS(Buffer);
2722 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2723 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2724 }
2725
2726 const Expr *Init = VD->getAnyInitializer();
2727 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2728 llvm::Constant *Ctor;
2729 llvm::Constant *ID;
2730 if (CGM.getLangOpts().OpenMPIsDevice) {
2731 // Generate function that re-emits the declaration's initializer into
2732 // the threadprivate copy of the variable VD
2733 CodeGenFunction CtorCGF(CGM);
2734
2735 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2736 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2737 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2738 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2739 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2740 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2741 FunctionArgList(), Loc, Loc);
2742 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2743 CtorCGF.EmitAnyExprToMem(Init,
2744 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2745 Init->getType().getQualifiers(),
2746 /*IsInitializer=*/true);
2747 CtorCGF.FinishFunction();
2748 Ctor = Fn;
2749 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002750 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002751 } else {
2752 Ctor = new llvm::GlobalVariable(
2753 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2754 llvm::GlobalValue::PrivateLinkage,
2755 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2756 ID = Ctor;
2757 }
2758
2759 // Register the information for the entry associated with the constructor.
2760 Out.clear();
2761 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2762 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002763 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002764 }
2765 if (VD->getType().isDestructedType() != QualType::DK_none) {
2766 llvm::Constant *Dtor;
2767 llvm::Constant *ID;
2768 if (CGM.getLangOpts().OpenMPIsDevice) {
2769 // Generate function that emits destructor call for the threadprivate
2770 // copy of the variable VD
2771 CodeGenFunction DtorCGF(CGM);
2772
2773 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2774 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2775 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2776 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2777 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2778 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2779 FunctionArgList(), Loc, Loc);
2780 // Create a scope with an artificial location for the body of this
2781 // function.
2782 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2783 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2784 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2785 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2786 DtorCGF.FinishFunction();
2787 Dtor = Fn;
2788 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002789 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002790 } else {
2791 Dtor = new llvm::GlobalVariable(
2792 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2793 llvm::GlobalValue::PrivateLinkage,
2794 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2795 ID = Dtor;
2796 }
2797 // Register the information for the entry associated with the destructor.
2798 Out.clear();
2799 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2800 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002801 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002802 }
2803 return CGM.getLangOpts().OpenMPIsDevice;
2804}
2805
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002806Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2807 QualType VarType,
2808 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002809 std::string Suffix = getName({"artificial", ""});
2810 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002811 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002812 llvm::Value *GAddr =
2813 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002814 llvm::Value *Args[] = {
2815 emitUpdateLocation(CGF, SourceLocation()),
2816 getThreadID(CGF, SourceLocation()),
2817 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2818 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2819 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002820 getOrCreateInternalVariable(
2821 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002822 return Address(
2823 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2824 CGF.EmitRuntimeCall(
2825 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2826 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2827 CGM.getPointerAlign());
2828}
2829
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002830void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2831 const RegionCodeGenTy &ThenGen,
2832 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002833 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2834
2835 // If the condition constant folds and can be elided, try to avoid emitting
2836 // the condition and the dead arm of the if/else.
2837 bool CondConstant;
2838 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002839 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002840 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002841 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002842 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002843 return;
2844 }
2845
2846 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2847 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002848 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2849 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2850 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002851 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2852
2853 // Emit the 'then' code.
2854 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002855 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002856 CGF.EmitBranch(ContBlock);
2857 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002858 // There is no need to emit line number for unconditional branch.
2859 (void)ApplyDebugLocation::CreateEmpty(CGF);
2860 CGF.EmitBlock(ElseBlock);
2861 ElseGen(CGF);
2862 // There is no need to emit line number for unconditional branch.
2863 (void)ApplyDebugLocation::CreateEmpty(CGF);
2864 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002865 // Emit the continuation block for code after the if.
2866 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002867}
2868
Alexey Bataev1d677132015-04-22 13:57:31 +00002869void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2870 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002871 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002872 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002873 if (!CGF.HaveInsertPoint())
2874 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002875 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002876 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2877 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002878 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002879 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002880 llvm::Value *Args[] = {
2881 RTLoc,
2882 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002883 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002884 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2885 RealArgs.append(std::begin(Args), std::end(Args));
2886 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2887
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002888 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002889 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2890 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002891 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2892 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002893 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2894 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002895 // Build calls:
2896 // __kmpc_serialized_parallel(&Loc, GTid);
2897 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002898 CGF.EmitRuntimeCall(
2899 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002900
Alexey Bataev1d677132015-04-22 13:57:31 +00002901 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002902 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2903 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002904 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002905 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataev8521ff62018-07-25 20:03:01 +00002906 // ThreadId for serialized parallels is 0.
2907 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002908 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2909 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002910 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002911
Alexey Bataev1d677132015-04-22 13:57:31 +00002912 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002913 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002914 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002915 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2916 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002917 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002918 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002919 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002920 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002921 RegionCodeGenTy ThenRCG(ThenGen);
2922 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002923 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002924}
2925
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002926// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002927// thread-ID variable (it is passed in a first argument of the outlined function
2928// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2929// regular serial code region, get thread ID by calling kmp_int32
2930// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2931// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002932Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2933 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002934 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002935 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002936 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002937 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002938
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002939 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2940 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002941 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002942 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002943 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002944 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002945
2946 return ThreadIDTemp;
2947}
2948
Alexey Bataev97720002014-11-11 04:05:39 +00002949llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002950CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002951 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002952 SmallString<256> Buffer;
2953 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002954 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002955 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002956 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002957 if (Elem.second) {
2958 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002959 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002960 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002961 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002962
David Blaikie13156b62014-11-19 03:06:06 +00002963 return Elem.second = new llvm::GlobalVariable(
2964 CGM.getModule(), Ty, /*IsConstant*/ false,
2965 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2966 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002967}
2968
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002969llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002970 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2971 std::string Name = getName({Prefix, "var"});
2972 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002973}
2974
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002975namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002976/// Common pre(post)-action for different OpenMP constructs.
2977class CommonActionTy final : public PrePostActionTy {
2978 llvm::Value *EnterCallee;
2979 ArrayRef<llvm::Value *> EnterArgs;
2980 llvm::Value *ExitCallee;
2981 ArrayRef<llvm::Value *> ExitArgs;
2982 bool Conditional;
2983 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002984
2985public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002986 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2987 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2988 bool Conditional = false)
2989 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2990 ExitArgs(ExitArgs), Conditional(Conditional) {}
2991 void Enter(CodeGenFunction &CGF) override {
2992 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2993 if (Conditional) {
2994 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2995 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2996 ContBlock = CGF.createBasicBlock("omp_if.end");
2997 // Generate the branch (If-stmt)
2998 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2999 CGF.EmitBlock(ThenBlock);
3000 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00003001 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003002 void Done(CodeGenFunction &CGF) {
3003 // Emit the rest of blocks/branches
3004 CGF.EmitBranch(ContBlock);
3005 CGF.EmitBlock(ContBlock, true);
3006 }
3007 void Exit(CodeGenFunction &CGF) override {
3008 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00003009 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003010};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003011} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003012
3013void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
3014 StringRef CriticalName,
3015 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00003016 SourceLocation Loc, const Expr *Hint) {
3017 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00003018 // CriticalOpGen();
3019 // __kmpc_end_critical(ident_t *, gtid, Lock);
3020 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00003021 if (!CGF.HaveInsertPoint())
3022 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00003023 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3024 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003025 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
3026 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00003027 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003028 EnterArgs.push_back(CGF.Builder.CreateIntCast(
3029 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
3030 }
3031 CommonActionTy Action(
3032 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
3033 : OMPRTL__kmpc_critical),
3034 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
3035 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00003036 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00003037}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003038
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003039void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003040 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003041 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003042 if (!CGF.HaveInsertPoint())
3043 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00003044 // if(__kmpc_master(ident_t *, gtid)) {
3045 // MasterOpGen();
3046 // __kmpc_end_master(ident_t *, gtid);
3047 // }
3048 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003049 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003050 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
3051 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
3052 /*Conditional=*/true);
3053 MasterOpGen.setAction(Action);
3054 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
3055 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00003056}
3057
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003058void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
3059 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003060 if (!CGF.HaveInsertPoint())
3061 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003062 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3063 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003064 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003065 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003066 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003067 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3068 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003069}
3070
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003071void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3072 const RegionCodeGenTy &TaskgroupOpGen,
3073 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003074 if (!CGF.HaveInsertPoint())
3075 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003076 // __kmpc_taskgroup(ident_t *, gtid);
3077 // TaskgroupOpGen();
3078 // __kmpc_end_taskgroup(ident_t *, gtid);
3079 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003080 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3081 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3082 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3083 Args);
3084 TaskgroupOpGen.setAction(Action);
3085 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003086}
3087
John McCall7f416cc2015-09-08 08:05:57 +00003088/// Given an array of pointers to variables, project the address of a
3089/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003090static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3091 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003092 // Pull out the pointer to the variable.
3093 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003094 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003095 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3096
3097 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003098 Addr = CGF.Builder.CreateElementBitCast(
3099 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003100 return Addr;
3101}
3102
Alexey Bataeva63048e2015-03-23 06:18:07 +00003103static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003104 CodeGenModule &CGM, llvm::Type *ArgsType,
3105 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003106 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3107 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003108 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003109 // void copy_func(void *LHSArg, void *RHSArg);
3110 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003111 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3112 ImplicitParamDecl::Other);
3113 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3114 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003115 Args.push_back(&LHSArg);
3116 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003117 const auto &CGFI =
3118 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003119 std::string Name =
3120 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3121 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3122 llvm::GlobalValue::InternalLinkage, Name,
3123 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003124 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003125 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003126 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003127 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003128 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003129 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003130 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3131 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3132 ArgsType), CGF.getPointerAlign());
3133 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3134 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3135 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003136 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3137 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3138 // ...
3139 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003140 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003141 const auto *DestVar =
3142 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003143 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3144
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003145 const auto *SrcVar =
3146 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003147 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3148
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003149 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003150 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003151 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003152 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003153 CGF.FinishFunction();
3154 return Fn;
3155}
3156
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003157void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003158 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003159 SourceLocation Loc,
3160 ArrayRef<const Expr *> CopyprivateVars,
3161 ArrayRef<const Expr *> SrcExprs,
3162 ArrayRef<const Expr *> DstExprs,
3163 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003164 if (!CGF.HaveInsertPoint())
3165 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003166 assert(CopyprivateVars.size() == SrcExprs.size() &&
3167 CopyprivateVars.size() == DstExprs.size() &&
3168 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003169 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003170 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003171 // if(__kmpc_single(ident_t *, gtid)) {
3172 // SingleOpGen();
3173 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003174 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003175 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003176 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3177 // <copy_func>, did_it);
3178
John McCall7f416cc2015-09-08 08:05:57 +00003179 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003180 if (!CopyprivateVars.empty()) {
3181 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003182 QualType KmpInt32Ty =
3183 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003184 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003185 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003186 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003187 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003188 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003189 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3190 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3191 /*Conditional=*/true);
3192 SingleOpGen.setAction(Action);
3193 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3194 if (DidIt.isValid()) {
3195 // did_it = 1;
3196 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3197 }
3198 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003199 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3200 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003201 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003202 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003203 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003204 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3205 /*IndexTypeQuals=*/0);
3206 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003207 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003208 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3209 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003210 Address Elem = CGF.Builder.CreateConstArrayGEP(
3211 CopyprivateList, I, CGF.getPointerSize());
3212 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003213 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003214 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3215 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003216 }
3217 // Build function that copies private values from single region to all other
3218 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003219 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003220 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003221 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003222 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003223 Address CL =
3224 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3225 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003226 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003227 llvm::Value *Args[] = {
3228 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3229 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003230 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003231 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003232 CpyFn, // void (*) (void *, void *) <copy_func>
3233 DidItVal // i32 did_it
3234 };
3235 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3236 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003237}
3238
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003239void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3240 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003241 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003242 if (!CGF.HaveInsertPoint())
3243 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003244 // __kmpc_ordered(ident_t *, gtid);
3245 // OrderedOpGen();
3246 // __kmpc_end_ordered(ident_t *, gtid);
3247 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003248 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003249 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003250 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3251 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3252 Args);
3253 OrderedOpGen.setAction(Action);
3254 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3255 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003256 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003257 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003258}
3259
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003260unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003261 unsigned Flags;
3262 if (Kind == OMPD_for)
3263 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3264 else if (Kind == OMPD_sections)
3265 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3266 else if (Kind == OMPD_single)
3267 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3268 else if (Kind == OMPD_barrier)
3269 Flags = OMP_IDENT_BARRIER_EXPL;
3270 else
3271 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003272 return Flags;
3273}
3274
3275void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
3276 OpenMPDirectiveKind Kind, bool EmitChecks,
3277 bool ForceSimpleCall) {
3278 if (!CGF.HaveInsertPoint())
3279 return;
3280 // Build call __kmpc_cancel_barrier(loc, thread_id);
3281 // Build call __kmpc_barrier(loc, thread_id);
3282 unsigned Flags = getDefaultFlagsForBarriers(Kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003283 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3284 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003285 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3286 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003287 if (auto *OMPRegionInfo =
3288 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003289 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003290 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003291 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003292 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003293 // if (__kmpc_cancel_barrier()) {
3294 // exit from construct;
3295 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003296 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3297 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3298 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003299 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3300 CGF.EmitBlock(ExitBB);
3301 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003302 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003303 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003304 CGF.EmitBranchThroughCleanup(CancelDestination);
3305 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3306 }
3307 return;
3308 }
3309 }
3310 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003311}
3312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003313/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003314static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003315 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003316 switch (ScheduleKind) {
3317 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003318 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3319 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003320 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003321 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003322 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003323 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003324 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003325 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3326 case OMPC_SCHEDULE_auto:
3327 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003328 case OMPC_SCHEDULE_unknown:
3329 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003330 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003331 }
3332 llvm_unreachable("Unexpected runtime schedule");
3333}
3334
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003335/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003336static OpenMPSchedType
3337getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3338 // only static is allowed for dist_schedule
3339 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3340}
3341
Alexander Musmanc6388682014-12-15 07:07:06 +00003342bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3343 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003344 OpenMPSchedType Schedule =
3345 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003346 return Schedule == OMP_sch_static;
3347}
3348
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003349bool CGOpenMPRuntime::isStaticNonchunked(
3350 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003351 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003352 return Schedule == OMP_dist_sch_static;
3353}
3354
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003355bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
3356 bool Chunked) const {
3357 OpenMPSchedType Schedule =
3358 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3359 return Schedule == OMP_sch_static_chunked;
3360}
3361
3362bool CGOpenMPRuntime::isStaticChunked(
3363 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3364 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3365 return Schedule == OMP_dist_sch_static_chunked;
3366}
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003367
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003368bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003369 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003370 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003371 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3372 return Schedule != OMP_sch_static;
3373}
3374
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003375static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3376 OpenMPScheduleClauseModifier M1,
3377 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003378 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003379 switch (M1) {
3380 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003381 Modifier = OMP_sch_modifier_monotonic;
3382 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003383 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003384 Modifier = OMP_sch_modifier_nonmonotonic;
3385 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003386 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003387 if (Schedule == OMP_sch_static_chunked)
3388 Schedule = OMP_sch_static_balanced_chunked;
3389 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003390 case OMPC_SCHEDULE_MODIFIER_last:
3391 case OMPC_SCHEDULE_MODIFIER_unknown:
3392 break;
3393 }
3394 switch (M2) {
3395 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003396 Modifier = OMP_sch_modifier_monotonic;
3397 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003398 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003399 Modifier = OMP_sch_modifier_nonmonotonic;
3400 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003401 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003402 if (Schedule == OMP_sch_static_chunked)
3403 Schedule = OMP_sch_static_balanced_chunked;
3404 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003405 case OMPC_SCHEDULE_MODIFIER_last:
3406 case OMPC_SCHEDULE_MODIFIER_unknown:
3407 break;
3408 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003409 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003410}
3411
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003412void CGOpenMPRuntime::emitForDispatchInit(
3413 CodeGenFunction &CGF, SourceLocation Loc,
3414 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3415 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003416 if (!CGF.HaveInsertPoint())
3417 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003418 OpenMPSchedType Schedule = getRuntimeSchedule(
3419 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003420 assert(Ordered ||
3421 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003422 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3423 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003424 // Call __kmpc_dispatch_init(
3425 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3426 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3427 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003428
John McCall7f416cc2015-09-08 08:05:57 +00003429 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003430 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3431 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003432 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003433 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3434 CGF.Builder.getInt32(addMonoNonMonoModifier(
3435 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003436 DispatchValues.LB, // Lower
3437 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003438 CGF.Builder.getIntN(IVSize, 1), // Stride
3439 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003440 };
3441 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3442}
3443
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003444static void emitForStaticInitCall(
3445 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3446 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3447 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003448 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003449 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003450 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003451
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003452 assert(!Values.Ordered);
3453 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3454 Schedule == OMP_sch_static_balanced_chunked ||
3455 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3456 Schedule == OMP_dist_sch_static ||
3457 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003458
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003459 // Call __kmpc_for_static_init(
3460 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3461 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3462 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3463 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3464 llvm::Value *Chunk = Values.Chunk;
3465 if (Chunk == nullptr) {
3466 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3467 Schedule == OMP_dist_sch_static) &&
3468 "expected static non-chunked schedule");
3469 // If the Chunk was not specified in the clause - use default value 1.
3470 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3471 } else {
3472 assert((Schedule == OMP_sch_static_chunked ||
3473 Schedule == OMP_sch_static_balanced_chunked ||
3474 Schedule == OMP_ord_static_chunked ||
3475 Schedule == OMP_dist_sch_static_chunked) &&
3476 "expected static chunked schedule");
3477 }
3478 llvm::Value *Args[] = {
3479 UpdateLocation,
3480 ThreadId,
3481 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3482 M2)), // Schedule type
3483 Values.IL.getPointer(), // &isLastIter
3484 Values.LB.getPointer(), // &LB
3485 Values.UB.getPointer(), // &UB
3486 Values.ST.getPointer(), // &Stride
3487 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3488 Chunk // Chunk
3489 };
3490 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003491}
3492
John McCall7f416cc2015-09-08 08:05:57 +00003493void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3494 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003495 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003496 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003497 const StaticRTInput &Values) {
3498 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3499 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3500 assert(isOpenMPWorksharingDirective(DKind) &&
3501 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003502 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003503 isOpenMPLoopDirective(DKind)
3504 ? OMP_IDENT_WORK_LOOP
3505 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003506 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3507 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003508 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003509 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003510 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003511}
John McCall7f416cc2015-09-08 08:05:57 +00003512
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003513void CGOpenMPRuntime::emitDistributeStaticInit(
3514 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003515 OpenMPDistScheduleClauseKind SchedKind,
3516 const CGOpenMPRuntime::StaticRTInput &Values) {
3517 OpenMPSchedType ScheduleNum =
3518 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003519 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003520 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003521 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3522 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003523 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003524 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3525 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003526 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003527}
3528
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003529void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003530 SourceLocation Loc,
3531 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003532 if (!CGF.HaveInsertPoint())
3533 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003534 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003535 llvm::Value *Args[] = {
3536 emitUpdateLocation(CGF, Loc,
3537 isOpenMPDistributeDirective(DKind)
3538 ? OMP_IDENT_WORK_DISTRIBUTE
3539 : isOpenMPLoopDirective(DKind)
3540 ? OMP_IDENT_WORK_LOOP
3541 : OMP_IDENT_WORK_SECTIONS),
3542 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003543 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3544 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003545}
3546
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003547void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3548 SourceLocation Loc,
3549 unsigned IVSize,
3550 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003551 if (!CGF.HaveInsertPoint())
3552 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003553 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003554 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003555 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3556}
3557
Alexander Musman92bdaab2015-03-12 13:37:50 +00003558llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3559 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003560 bool IVSigned, Address IL,
3561 Address LB, Address UB,
3562 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003563 // Call __kmpc_dispatch_next(
3564 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3565 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3566 // kmp_int[32|64] *p_stride);
3567 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003568 emitUpdateLocation(CGF, Loc),
3569 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003570 IL.getPointer(), // &isLastIter
3571 LB.getPointer(), // &Lower
3572 UB.getPointer(), // &Upper
3573 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003574 };
3575 llvm::Value *Call =
3576 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3577 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003578 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003579 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003580}
3581
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003582void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3583 llvm::Value *NumThreads,
3584 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003585 if (!CGF.HaveInsertPoint())
3586 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003587 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3588 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003589 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003590 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003591 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3592 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003593}
3594
Alexey Bataev7f210c62015-06-18 13:40:03 +00003595void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3596 OpenMPProcBindClauseKind ProcBind,
3597 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003598 if (!CGF.HaveInsertPoint())
3599 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003600 // Constants for proc bind value accepted by the runtime.
3601 enum ProcBindTy {
3602 ProcBindFalse = 0,
3603 ProcBindTrue,
3604 ProcBindMaster,
3605 ProcBindClose,
3606 ProcBindSpread,
3607 ProcBindIntel,
3608 ProcBindDefault
3609 } RuntimeProcBind;
3610 switch (ProcBind) {
3611 case OMPC_PROC_BIND_master:
3612 RuntimeProcBind = ProcBindMaster;
3613 break;
3614 case OMPC_PROC_BIND_close:
3615 RuntimeProcBind = ProcBindClose;
3616 break;
3617 case OMPC_PROC_BIND_spread:
3618 RuntimeProcBind = ProcBindSpread;
3619 break;
3620 case OMPC_PROC_BIND_unknown:
3621 llvm_unreachable("Unsupported proc_bind value.");
3622 }
3623 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3624 llvm::Value *Args[] = {
3625 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3626 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3627 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3628}
3629
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003630void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3631 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003632 if (!CGF.HaveInsertPoint())
3633 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003634 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003635 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3636 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003637}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003638
Alexey Bataev62b63b12015-03-10 07:28:44 +00003639namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003640/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003641enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003642 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003643 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003644 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003645 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003646 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003647 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003648 /// Function with call of destructors for private variables.
3649 Data1,
3650 /// Task priority.
3651 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003652 /// (Taskloops only) Lower bound.
3653 KmpTaskTLowerBound,
3654 /// (Taskloops only) Upper bound.
3655 KmpTaskTUpperBound,
3656 /// (Taskloops only) Stride.
3657 KmpTaskTStride,
3658 /// (Taskloops only) Is last iteration flag.
3659 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003660 /// (Taskloops only) Reduction data.
3661 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003662};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003663} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003664
Samuel Antaoee8fb302016-01-06 13:42:12 +00003665bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003666 return OffloadEntriesTargetRegion.empty() &&
3667 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003668}
3669
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003670/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003671void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3672 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3673 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003674 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003675 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3676 "only required for the device "
3677 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003678 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003679 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003680 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003681 ++OffloadingEntriesNum;
3682}
3683
3684void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3685 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3686 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003687 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003688 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003689 // If we are emitting code for a target, the entry is already initialized,
3690 // only has to be registered.
3691 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003692 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3693 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3694 DiagnosticsEngine::Error,
3695 "Unable to find target region on line '%0' in the device code.");
3696 CGM.getDiags().Report(DiagID) << LineNum;
3697 return;
3698 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003699 auto &Entry =
3700 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003701 assert(Entry.isValid() && "Entry not initialized!");
3702 Entry.setAddress(Addr);
3703 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003704 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003705 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003706 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003707 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003708 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003709 }
3710}
3711
3712bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003713 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3714 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003715 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3716 if (PerDevice == OffloadEntriesTargetRegion.end())
3717 return false;
3718 auto PerFile = PerDevice->second.find(FileID);
3719 if (PerFile == PerDevice->second.end())
3720 return false;
3721 auto PerParentName = PerFile->second.find(ParentName);
3722 if (PerParentName == PerFile->second.end())
3723 return false;
3724 auto PerLine = PerParentName->second.find(LineNum);
3725 if (PerLine == PerParentName->second.end())
3726 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003727 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003728 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003729 return false;
3730 return true;
3731}
3732
3733void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3734 const OffloadTargetRegionEntryInfoActTy &Action) {
3735 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003736 for (const auto &D : OffloadEntriesTargetRegion)
3737 for (const auto &F : D.second)
3738 for (const auto &P : F.second)
3739 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003740 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003741}
3742
Alexey Bataev03f270c2018-03-30 18:31:07 +00003743void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3744 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3745 OMPTargetGlobalVarEntryKind Flags,
3746 unsigned Order) {
3747 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3748 "only required for the device "
3749 "code generation.");
3750 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3751 ++OffloadingEntriesNum;
3752}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003753
Alexey Bataev03f270c2018-03-30 18:31:07 +00003754void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3755 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3756 CharUnits VarSize,
3757 OMPTargetGlobalVarEntryKind Flags,
3758 llvm::GlobalValue::LinkageTypes Linkage) {
3759 if (CGM.getLangOpts().OpenMPIsDevice) {
3760 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3761 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3762 "Entry not initialized!");
3763 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3764 "Resetting with the new address.");
3765 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3766 return;
3767 Entry.setAddress(Addr);
3768 Entry.setVarSize(VarSize);
3769 Entry.setLinkage(Linkage);
3770 } else {
3771 if (hasDeviceGlobalVarEntryInfo(VarName))
3772 return;
3773 OffloadEntriesDeviceGlobalVar.try_emplace(
3774 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3775 ++OffloadingEntriesNum;
3776 }
3777}
3778
3779void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3780 actOnDeviceGlobalVarEntriesInfo(
3781 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3782 // Scan all target region entries and perform the provided action.
3783 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3784 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003785}
3786
3787llvm::Function *
3788CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003789 // If we don't have entries or if we are emitting code for the device, we
3790 // don't need to do anything.
3791 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3792 return nullptr;
3793
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003794 llvm::Module &M = CGM.getModule();
3795 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003796
3797 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003798 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003799
3800 // We should be creating an offloading descriptor only if there are devices
3801 // specified.
3802 assert(!Devices.empty() && "No OpenMP offloading devices??");
3803
3804 // Create the external variables that will point to the begin and end of the
3805 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003806 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003807 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003808 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003809 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003810 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003811 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003812 EntriesBeginName);
3813 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3814 auto *HostEntriesEnd =
3815 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3816 llvm::GlobalValue::ExternalLinkage,
3817 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003818
3819 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003820 auto *DeviceImageTy = cast<llvm::StructType>(
3821 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003822 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003823 ConstantArrayBuilder DeviceImagesEntries =
3824 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003825
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003826 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003827 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003828 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003829 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003830 M, CGM.Int8Ty, /*isConstant=*/true,
3831 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003832 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3833 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003834 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003835 M, CGM.Int8Ty, /*isConstant=*/true,
3836 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003837 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003838
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003839 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3840 HostEntriesEnd};
3841 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3842 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003843 }
3844
3845 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003846 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003847 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003848 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3849 CGM.getPointerAlign(),
3850 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003851 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003852
3853 // This is a Zero array to be used in the creation of the constant expressions
3854 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3855 llvm::Constant::getNullValue(CGM.Int32Ty)};
3856
3857 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003858 llvm::Constant *Data[] = {
3859 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3860 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3861 DeviceImages, Index),
3862 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003863 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003864 llvm::GlobalVariable *Desc = createGlobalStruct(
3865 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003866
3867 // Emit code to register or unregister the descriptor at execution
3868 // startup or closing, respectively.
3869
Alexey Bataev03f270c2018-03-30 18:31:07 +00003870 llvm::Function *UnRegFn;
3871 {
3872 FunctionArgList Args;
3873 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3874 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003875
Alexey Bataev03f270c2018-03-30 18:31:07 +00003876 CodeGenFunction CGF(CGM);
3877 // Disable debug info for global (de-)initializer because they are not part
3878 // of some particular construct.
3879 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003880 const auto &FI =
3881 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3882 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003883 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3884 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003885 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3886 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3887 Desc);
3888 CGF.FinishFunction();
3889 }
3890 llvm::Function *RegFn;
3891 {
3892 CodeGenFunction CGF(CGM);
3893 // Disable debug info for global (de-)initializer because they are not part
3894 // of some particular construct.
3895 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003896 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003897 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003898
3899 // Encode offload target triples into the registration function name. It
3900 // will serve as a comdat key for the registration/unregistration code for
3901 // this particular combination of offloading targets.
3902 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3903 RegFnNameParts[0] = "omp_offloading";
3904 RegFnNameParts[1] = "descriptor_reg";
3905 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3906 [](const llvm::Triple &T) -> const std::string& {
3907 return T.getTriple();
3908 });
3909 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3910 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003911 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003912 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3913 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3914 // Create a variable to drive the registration and unregistration of the
3915 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3916 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3917 SourceLocation(), nullptr, C.CharTy,
3918 ImplicitParamDecl::Other);
3919 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3920 CGF.FinishFunction();
3921 }
George Rokos29d0f002017-05-27 03:03:13 +00003922 if (CGM.supportsCOMDAT()) {
3923 // It is sufficient to call registration function only once, so create a
3924 // COMDAT group for registration/unregistration functions and associated
3925 // data. That would reduce startup time and code size. Registration
3926 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003927 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003928 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3929 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3930 RegFn->setComdat(ComdatKey);
3931 UnRegFn->setComdat(ComdatKey);
3932 DeviceImages->setComdat(ComdatKey);
3933 Desc->setComdat(ComdatKey);
3934 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003935 return RegFn;
3936}
3937
Alexey Bataev03f270c2018-03-30 18:31:07 +00003938void CGOpenMPRuntime::createOffloadEntry(
3939 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3940 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003941 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003942 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003943 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003944
3945 // Create constant string with the name.
3946 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3947
Alexey Bataev18fa2322018-05-02 14:20:50 +00003948 std::string StringName = getName({"omp_offloading", "entry_name"});
3949 auto *Str = new llvm::GlobalVariable(
3950 M, StrPtrInit->getType(), /*isConstant=*/true,
3951 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003952 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003953
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003954 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3955 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3956 llvm::ConstantInt::get(CGM.SizeTy, Size),
3957 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3958 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003959 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003960 llvm::GlobalVariable *Entry = createGlobalStruct(
3961 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3962 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003963
3964 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003965 std::string Section = getName({"omp_offloading", "entries"});
3966 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003967}
3968
3969void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3970 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003971 // can easily figure out what to emit. The produced metadata looks like
3972 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003973 //
3974 // !omp_offload.info = !{!1, ...}
3975 //
3976 // Right now we only generate metadata for function that contain target
3977 // regions.
3978
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003979 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003980 if (OffloadEntriesInfoManager.empty())
3981 return;
3982
3983 llvm::Module &M = CGM.getModule();
3984 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003985 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003986 OrderedEntries(OffloadEntriesInfoManager.size());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003987 llvm::SmallVector<StringRef, 16> ParentFunctions(
3988 OffloadEntriesInfoManager.size());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003989
Simon Pilgrim2c518802017-03-30 14:13:19 +00003990 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003991 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003992 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003993 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003994 };
3995
Alexey Bataev03f270c2018-03-30 18:31:07 +00003996 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3997
3998 // Create the offloading info metadata node.
3999 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004000
4001 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00004002 auto &&TargetRegionMetadataEmitter =
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004003 [&C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt, &GetMDString](
Alexey Bataev03f270c2018-03-30 18:31:07 +00004004 unsigned DeviceID, unsigned FileID, StringRef ParentName,
4005 unsigned Line,
4006 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
4007 // Generate metadata for target regions. Each entry of this metadata
4008 // contains:
4009 // - Entry 0 -> Kind of this type of metadata (0).
4010 // - Entry 1 -> Device ID of the file where the entry was identified.
4011 // - Entry 2 -> File ID of the file where the entry was identified.
4012 // - Entry 3 -> Mangled name of the function where the entry was
4013 // identified.
4014 // - Entry 4 -> Line in the file where the entry was identified.
4015 // - Entry 5 -> Order the entry was created.
4016 // The first element of the metadata node is the kind.
4017 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
4018 GetMDInt(FileID), GetMDString(ParentName),
4019 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00004020
Alexey Bataev03f270c2018-03-30 18:31:07 +00004021 // Save this entry in the right position of the ordered entries array.
4022 OrderedEntries[E.getOrder()] = &E;
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004023 ParentFunctions[E.getOrder()] = ParentName;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004024
Alexey Bataev03f270c2018-03-30 18:31:07 +00004025 // Add metadata to the named metadata node.
4026 MD->addOperand(llvm::MDNode::get(C, Ops));
4027 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00004028
4029 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
4030 TargetRegionMetadataEmitter);
4031
Alexey Bataev03f270c2018-03-30 18:31:07 +00004032 // Create function that emits metadata for each device global variable entry;
4033 auto &&DeviceGlobalVarMetadataEmitter =
4034 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
4035 MD](StringRef MangledName,
4036 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
4037 &E) {
4038 // Generate metadata for global variables. Each entry of this metadata
4039 // contains:
4040 // - Entry 0 -> Kind of this type of metadata (1).
4041 // - Entry 1 -> Mangled name of the variable.
4042 // - Entry 2 -> Declare target kind.
4043 // - Entry 3 -> Order the entry was created.
4044 // The first element of the metadata node is the kind.
4045 llvm::Metadata *Ops[] = {
4046 GetMDInt(E.getKind()), GetMDString(MangledName),
4047 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
4048
4049 // Save this entry in the right position of the ordered entries array.
4050 OrderedEntries[E.getOrder()] = &E;
4051
4052 // Add metadata to the named metadata node.
4053 MD->addOperand(llvm::MDNode::get(C, Ops));
4054 };
4055
4056 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
4057 DeviceGlobalVarMetadataEmitter);
4058
4059 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004060 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004061 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00004062 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
4063 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004064 if (!CE->getID() || !CE->getAddress()) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004065 // Do not blame the entry if the parent funtion is not emitted.
4066 StringRef FnName = ParentFunctions[CE->getOrder()];
4067 if (!CGM.GetGlobalValue(FnName))
4068 continue;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004069 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4070 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00004071 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004072 "address or the ID is invalid.");
4073 CGM.getDiags().Report(DiagID);
4074 continue;
4075 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00004076 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004077 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
4078 } else if (const auto *CE =
4079 dyn_cast<OffloadEntriesInfoManagerTy::
4080 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004081 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
4082 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4083 CE->getFlags());
4084 switch (Flags) {
4085 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
4086 if (!CE->getAddress()) {
4087 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4088 DiagnosticsEngine::Error,
4089 "Offloading entry for declare target variable is incorrect: the "
4090 "address is invalid.");
4091 CGM.getDiags().Report(DiagID);
4092 continue;
4093 }
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00004094 // The vaiable has no definition - no need to add the entry.
4095 if (CE->getVarSize().isZero())
4096 continue;
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004097 break;
4098 }
4099 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
4100 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4101 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4102 "Declaret target link address is set.");
4103 if (CGM.getLangOpts().OpenMPIsDevice)
4104 continue;
4105 if (!CE->getAddress()) {
4106 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4107 DiagnosticsEngine::Error,
4108 "Offloading entry for declare target variable is incorrect: the "
4109 "address is invalid.");
4110 CGM.getDiags().Report(DiagID);
4111 continue;
4112 }
4113 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004114 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004115 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004116 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004117 CE->getLinkage());
4118 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004119 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004120 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004121 }
4122}
4123
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004124/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004125/// metadata.
4126void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4127 // If we are in target mode, load the metadata from the host IR. This code has
4128 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4129
4130 if (!CGM.getLangOpts().OpenMPIsDevice)
4131 return;
4132
4133 if (CGM.getLangOpts().OMPHostIRFile.empty())
4134 return;
4135
4136 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004137 if (auto EC = Buf.getError()) {
4138 CGM.getDiags().Report(diag::err_cannot_open_file)
4139 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004140 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004141 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004142
4143 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004144 auto ME = expectedToErrorOrAndEmitErrors(
4145 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004146
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004147 if (auto EC = ME.getError()) {
4148 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4149 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4150 CGM.getDiags().Report(DiagID)
4151 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004152 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004153 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004154
4155 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4156 if (!MD)
4157 return;
4158
George Burgess IV00f70bd2018-03-01 05:43:23 +00004159 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004160 auto &&GetMDInt = [MN](unsigned Idx) {
4161 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004162 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4163 };
4164
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004165 auto &&GetMDString = [MN](unsigned Idx) {
4166 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004167 return V->getString();
4168 };
4169
Alexey Bataev03f270c2018-03-30 18:31:07 +00004170 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004171 default:
4172 llvm_unreachable("Unexpected metadata!");
4173 break;
4174 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004175 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004176 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004177 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4178 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4179 /*Order=*/GetMDInt(5));
4180 break;
4181 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4182 OffloadingEntryInfoDeviceGlobalVar:
4183 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4184 /*MangledName=*/GetMDString(1),
4185 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4186 /*Flags=*/GetMDInt(2)),
4187 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004188 break;
4189 }
4190 }
4191}
4192
Alexey Bataev62b63b12015-03-10 07:28:44 +00004193void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4194 if (!KmpRoutineEntryPtrTy) {
4195 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004196 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004197 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4198 FunctionProtoType::ExtProtoInfo EPI;
4199 KmpRoutineEntryPtrQTy = C.getPointerType(
4200 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4201 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4202 }
4203}
4204
Samuel Antaoee8fb302016-01-06 13:42:12 +00004205QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004206 // Make sure the type of the entry is already created. This is the type we
4207 // have to create:
4208 // struct __tgt_offload_entry{
4209 // void *addr; // Pointer to the offload entry info.
4210 // // (function or global)
4211 // char *name; // Name of the function or global.
4212 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004213 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4214 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004215 // };
4216 if (TgtOffloadEntryQTy.isNull()) {
4217 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004218 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004219 RD->startDefinition();
4220 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4221 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4222 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004223 addFieldToRecordDecl(
4224 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4225 addFieldToRecordDecl(
4226 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004227 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004228 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004229 TgtOffloadEntryQTy = C.getRecordType(RD);
4230 }
4231 return TgtOffloadEntryQTy;
4232}
4233
4234QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4235 // These are the types we need to build:
4236 // struct __tgt_device_image{
4237 // void *ImageStart; // Pointer to the target code start.
4238 // void *ImageEnd; // Pointer to the target code end.
4239 // // We also add the host entries to the device image, as it may be useful
4240 // // for the target runtime to have access to that information.
4241 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4242 // // the entries.
4243 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4244 // // entries (non inclusive).
4245 // };
4246 if (TgtDeviceImageQTy.isNull()) {
4247 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004248 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004249 RD->startDefinition();
4250 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4251 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4252 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4253 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4254 RD->completeDefinition();
4255 TgtDeviceImageQTy = C.getRecordType(RD);
4256 }
4257 return TgtDeviceImageQTy;
4258}
4259
4260QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4261 // struct __tgt_bin_desc{
4262 // int32_t NumDevices; // Number of devices supported.
4263 // __tgt_device_image *DeviceImages; // Arrays of device images
4264 // // (one per device).
4265 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4266 // // entries.
4267 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4268 // // entries (non inclusive).
4269 // };
4270 if (TgtBinaryDescriptorQTy.isNull()) {
4271 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004272 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004273 RD->startDefinition();
4274 addFieldToRecordDecl(
4275 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4276 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4277 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4278 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4279 RD->completeDefinition();
4280 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4281 }
4282 return TgtBinaryDescriptorQTy;
4283}
4284
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004285namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004286struct PrivateHelpersTy {
4287 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4288 const VarDecl *PrivateElemInit)
4289 : Original(Original), PrivateCopy(PrivateCopy),
4290 PrivateElemInit(PrivateElemInit) {}
4291 const VarDecl *Original;
4292 const VarDecl *PrivateCopy;
4293 const VarDecl *PrivateElemInit;
4294};
4295typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004296} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004297
Alexey Bataev9e034042015-05-05 04:05:12 +00004298static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004299createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004300 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004301 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004302 // Build struct .kmp_privates_t. {
4303 // /* private vars */
4304 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004305 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004306 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004307 for (const auto &Pair : Privates) {
4308 const VarDecl *VD = Pair.second.Original;
4309 QualType Type = VD->getType().getNonReferenceType();
4310 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004311 if (VD->hasAttrs()) {
4312 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4313 E(VD->getAttrs().end());
4314 I != E; ++I)
4315 FD->addAttr(*I);
4316 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004317 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004318 RD->completeDefinition();
4319 return RD;
4320 }
4321 return nullptr;
4322}
4323
Alexey Bataev9e034042015-05-05 04:05:12 +00004324static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004325createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4326 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004327 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004328 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004329 // Build struct kmp_task_t {
4330 // void * shareds;
4331 // kmp_routine_entry_t routine;
4332 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004333 // kmp_cmplrdata_t data1;
4334 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004335 // For taskloops additional fields:
4336 // kmp_uint64 lb;
4337 // kmp_uint64 ub;
4338 // kmp_int64 st;
4339 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004340 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004341 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004342 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004343 UD->startDefinition();
4344 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4345 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4346 UD->completeDefinition();
4347 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004348 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004349 RD->startDefinition();
4350 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4351 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4352 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004353 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4354 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004355 if (isOpenMPTaskLoopDirective(Kind)) {
4356 QualType KmpUInt64Ty =
4357 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4358 QualType KmpInt64Ty =
4359 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4360 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4361 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4362 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4363 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004364 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004365 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004366 RD->completeDefinition();
4367 return RD;
4368}
4369
4370static RecordDecl *
4371createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004372 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004373 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004374 // Build struct kmp_task_t_with_privates {
4375 // kmp_task_t task_data;
4376 // .kmp_privates_t. privates;
4377 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004378 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004379 RD->startDefinition();
4380 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004381 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004382 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004383 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004384 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004385}
4386
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004387/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004388/// argument.
4389/// \code
4390/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004391/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004392/// For taskloops:
4393/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004394/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004395/// return 0;
4396/// }
4397/// \endcode
4398static llvm::Value *
4399emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004400 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4401 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004402 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004403 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4404 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004405 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004406 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004407 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4408 ImplicitParamDecl::Other);
4409 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4410 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4411 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004412 Args.push_back(&GtidArg);
4413 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004414 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004415 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004416 llvm::FunctionType *TaskEntryTy =
4417 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004418 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4419 auto *TaskEntry = llvm::Function::Create(
4420 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004421 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004422 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004423 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004424 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4425 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004426
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004427 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004428 // tt,
4429 // For taskloops:
4430 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4431 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004432 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004433 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004434 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4435 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4436 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004437 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004438 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004439 LValue Base =
4440 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004441 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004442 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004443 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4444 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004445
4446 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004447 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4448 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004449 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004450 CGF.ConvertTypeForMem(SharedsPtrTy));
4451
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004452 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4453 llvm::Value *PrivatesParam;
4454 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004455 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004456 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004457 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004458 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004459 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004460 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004461
Alexey Bataev7292c292016-04-25 12:22:29 +00004462 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4463 TaskPrivatesMap,
4464 CGF.Builder
4465 .CreatePointerBitCastOrAddrSpaceCast(
4466 TDBase.getAddress(), CGF.VoidPtrTy)
4467 .getPointer()};
4468 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4469 std::end(CommonArgs));
4470 if (isOpenMPTaskLoopDirective(Kind)) {
4471 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004472 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4473 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004474 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004475 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4476 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004477 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004478 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4479 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004480 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004481 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4482 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004483 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004484 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4485 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004486 CallArgs.push_back(LBParam);
4487 CallArgs.push_back(UBParam);
4488 CallArgs.push_back(StParam);
4489 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004490 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004491 }
4492 CallArgs.push_back(SharedsParam);
4493
Alexey Bataev3c595a62017-08-14 15:01:03 +00004494 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4495 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004496 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4497 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004498 CGF.FinishFunction();
4499 return TaskEntry;
4500}
4501
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004502static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4503 SourceLocation Loc,
4504 QualType KmpInt32Ty,
4505 QualType KmpTaskTWithPrivatesPtrQTy,
4506 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004507 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004508 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004509 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4510 ImplicitParamDecl::Other);
4511 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4512 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4513 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004514 Args.push_back(&GtidArg);
4515 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004516 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004517 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004518 llvm::FunctionType *DestructorFnTy =
4519 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004520 std::string Name =
4521 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004522 auto *DestructorFn =
4523 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004524 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004525 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004526 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004527 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004528 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004529 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004530 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004531
Alexey Bataev31300ed2016-02-04 11:27:03 +00004532 LValue Base = CGF.EmitLoadOfPointerLValue(
4533 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4534 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004535 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004536 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4537 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004538 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004539 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004540 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004541 if (QualType::DestructionKind DtorKind =
4542 Field->getType().isDestructedType()) {
4543 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004544 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4545 }
4546 }
4547 CGF.FinishFunction();
4548 return DestructorFn;
4549}
4550
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004551/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004552/// firstprivate variables.
4553/// \code
4554/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4555/// **noalias priv1,..., <tyn> **noalias privn) {
4556/// *priv1 = &.privates.priv1;
4557/// ...;
4558/// *privn = &.privates.privn;
4559/// }
4560/// \endcode
4561static llvm::Value *
4562emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004563 ArrayRef<const Expr *> PrivateVars,
4564 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004565 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004566 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004567 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004568 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004569 FunctionArgList Args;
4570 ImplicitParamDecl TaskPrivatesArg(
4571 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004572 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4573 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004574 Args.push_back(&TaskPrivatesArg);
4575 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4576 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004577 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004578 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004579 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4580 C.getPointerType(C.getPointerType(E->getType()))
4581 .withConst()
4582 .withRestrict(),
4583 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004584 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004585 PrivateVarsPos[VD] = Counter;
4586 ++Counter;
4587 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004588 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004589 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004590 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4591 C.getPointerType(C.getPointerType(E->getType()))
4592 .withConst()
4593 .withRestrict(),
4594 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004595 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004596 PrivateVarsPos[VD] = Counter;
4597 ++Counter;
4598 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004599 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004600 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004601 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4602 C.getPointerType(C.getPointerType(E->getType()))
4603 .withConst()
4604 .withRestrict(),
4605 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004606 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004607 PrivateVarsPos[VD] = Counter;
4608 ++Counter;
4609 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004610 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004611 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004612 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004613 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004614 std::string Name =
4615 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004616 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004617 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4618 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004619 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004620 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004621 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004622 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004623 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004624 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004625 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004626 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004627
4628 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004629 LValue Base = CGF.EmitLoadOfPointerLValue(
4630 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4631 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004632 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004633 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004634 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4635 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4636 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4637 LValue RefLVal =
4638 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4639 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004640 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004641 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004642 ++Counter;
4643 }
4644 CGF.FinishFunction();
4645 return TaskPrivatesMap;
4646}
4647
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004648static bool stable_sort_comparator(const PrivateDataTy P1,
4649 const PrivateDataTy P2) {
4650 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004651}
4652
Alexey Bataevf93095a2016-05-05 08:46:22 +00004653/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004654static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004655 const OMPExecutableDirective &D,
4656 Address KmpTaskSharedsPtr, LValue TDBase,
4657 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4658 QualType SharedsTy, QualType SharedsPtrTy,
4659 const OMPTaskDataTy &Data,
4660 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004661 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004662 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4663 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004664 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4665 ? OMPD_taskloop
4666 : OMPD_task;
4667 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4668 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004669 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004670 bool IsTargetTask =
4671 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4672 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4673 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4674 // PointersArray and SizesArray. The original variables for these arrays are
4675 // not captured and we get their addresses explicitly.
4676 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004677 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004678 SrcBase = CGF.MakeAddrLValue(
4679 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4680 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4681 SharedsTy);
4682 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004683 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004684 for (const PrivateDataTy &Pair : Privates) {
4685 const VarDecl *VD = Pair.second.PrivateCopy;
4686 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004687 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4688 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004689 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004690 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4691 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004692 // Check if the variable is the target-based BasePointersArray,
4693 // PointersArray or SizesArray.
4694 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004695 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004696 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004697 if (IsTargetTask && !SharedField) {
4698 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4699 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4700 cast<CapturedDecl>(OriginalVD->getDeclContext())
4701 ->getNumParams() == 0 &&
4702 isa<TranslationUnitDecl>(
4703 cast<CapturedDecl>(OriginalVD->getDeclContext())
4704 ->getDeclContext()) &&
4705 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004706 SharedRefLValue =
4707 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4708 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004709 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4710 SharedRefLValue = CGF.MakeAddrLValue(
4711 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4712 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4713 SharedRefLValue.getTBAAInfo());
4714 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004715 if (Type->isArrayType()) {
4716 // Initialize firstprivate array.
4717 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4718 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004719 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004720 } else {
4721 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004722 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004723 CGF.EmitOMPAggregateAssign(
4724 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4725 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4726 Address SrcElement) {
4727 // Clean up any temporaries needed by the initialization.
4728 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4729 InitScope.addPrivate(
4730 Elem, [SrcElement]() -> Address { return SrcElement; });
4731 (void)InitScope.Privatize();
4732 // Emit initialization for single element.
4733 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4734 CGF, &CapturesInfo);
4735 CGF.EmitAnyExprToMem(Init, DestElement,
4736 Init->getType().getQualifiers(),
4737 /*IsInitializer=*/false);
4738 });
4739 }
4740 } else {
4741 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4742 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4743 return SharedRefLValue.getAddress();
4744 });
4745 (void)InitScope.Privatize();
4746 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4747 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4748 /*capturedByInit=*/false);
4749 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004750 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004751 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004752 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004753 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004754 ++FI;
4755 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004756}
4757
4758/// Check if duplication function is required for taskloops.
4759static bool checkInitIsRequired(CodeGenFunction &CGF,
4760 ArrayRef<PrivateDataTy> Privates) {
4761 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004762 for (const PrivateDataTy &Pair : Privates) {
4763 const VarDecl *VD = Pair.second.PrivateCopy;
4764 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004765 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4766 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004767 if (InitRequired)
4768 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004769 }
4770 return InitRequired;
4771}
4772
4773
4774/// Emit task_dup function (for initialization of
4775/// private/firstprivate/lastprivate vars and last_iter flag)
4776/// \code
4777/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4778/// lastpriv) {
4779/// // setup lastprivate flag
4780/// task_dst->last = lastpriv;
4781/// // could be constructor calls here...
4782/// }
4783/// \endcode
4784static llvm::Value *
4785emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4786 const OMPExecutableDirective &D,
4787 QualType KmpTaskTWithPrivatesPtrQTy,
4788 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4789 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4790 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4791 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004792 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004793 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004794 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4795 KmpTaskTWithPrivatesPtrQTy,
4796 ImplicitParamDecl::Other);
4797 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4798 KmpTaskTWithPrivatesPtrQTy,
4799 ImplicitParamDecl::Other);
4800 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4801 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004802 Args.push_back(&DstArg);
4803 Args.push_back(&SrcArg);
4804 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004805 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004806 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004807 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004808 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4809 auto *TaskDup = llvm::Function::Create(
4810 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004811 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004812 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004813 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004814 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4815 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004816
4817 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4818 CGF.GetAddrOfLocalVar(&DstArg),
4819 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4820 // task_dst->liter = lastpriv;
4821 if (WithLastIter) {
4822 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4823 LValue Base = CGF.EmitLValueForField(
4824 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4825 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4826 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4827 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4828 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4829 }
4830
4831 // Emit initial values for private copies (if any).
4832 assert(!Privates.empty());
4833 Address KmpTaskSharedsPtr = Address::invalid();
4834 if (!Data.FirstprivateVars.empty()) {
4835 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4836 CGF.GetAddrOfLocalVar(&SrcArg),
4837 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4838 LValue Base = CGF.EmitLValueForField(
4839 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4840 KmpTaskSharedsPtr = Address(
4841 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4842 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4843 KmpTaskTShareds)),
4844 Loc),
4845 CGF.getNaturalTypeAlignment(SharedsTy));
4846 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004847 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4848 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004849 CGF.FinishFunction();
4850 return TaskDup;
4851}
4852
Alexey Bataev8a831592016-05-10 10:36:51 +00004853/// Checks if destructor function is required to be generated.
4854/// \return true if cleanups are required, false otherwise.
4855static bool
4856checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4857 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004858 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4859 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4860 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004861 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4862 if (NeedsCleanup)
4863 break;
4864 }
4865 return NeedsCleanup;
4866}
4867
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004868CGOpenMPRuntime::TaskResultTy
4869CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4870 const OMPExecutableDirective &D,
4871 llvm::Value *TaskFunction, QualType SharedsTy,
4872 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004873 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004874 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004875 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004876 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004877 for (const Expr *E : Data.PrivateVars) {
4878 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004879 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004880 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004881 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004882 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004883 ++I;
4884 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004885 I = Data.FirstprivateCopies.begin();
4886 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004887 for (const Expr *E : Data.FirstprivateVars) {
4888 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004889 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004890 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004891 PrivateHelpersTy(
4892 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004893 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004894 ++I;
4895 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004896 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004897 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004898 for (const Expr *E : Data.LastprivateVars) {
4899 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004900 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004901 C.getDeclAlign(VD),
4902 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004903 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004904 ++I;
4905 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004906 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004907 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004908 // Build type kmp_routine_entry_t (if not built yet).
4909 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004910 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004911 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4912 if (SavedKmpTaskloopTQTy.isNull()) {
4913 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4914 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4915 }
4916 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004917 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004918 assert((D.getDirectiveKind() == OMPD_task ||
4919 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4920 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4921 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004922 if (SavedKmpTaskTQTy.isNull()) {
4923 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4924 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4925 }
4926 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004927 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004928 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004929 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004930 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004931 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004932 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004933 QualType KmpTaskTWithPrivatesPtrQTy =
4934 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004935 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4936 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4937 KmpTaskTWithPrivatesTy->getPointerTo();
4938 llvm::Value *KmpTaskTWithPrivatesTySize =
4939 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004940 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4941
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004942 // Emit initial values for private copies (if any).
4943 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004944 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004945 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004946 if (!Privates.empty()) {
4947 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004948 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4949 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4950 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004951 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4952 TaskPrivatesMap, TaskPrivatesMapTy);
4953 } else {
4954 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4955 cast<llvm::PointerType>(TaskPrivatesMapTy));
4956 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004957 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4958 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004959 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004960 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4961 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4962 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004963
4964 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4965 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4966 // kmp_routine_entry_t *task_entry);
4967 // Task flags. Format is taken from
4968 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4969 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004970 enum {
4971 TiedFlag = 0x1,
4972 FinalFlag = 0x2,
4973 DestructorsFlag = 0x8,
4974 PriorityFlag = 0x20
4975 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004976 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004977 bool NeedsCleanup = false;
4978 if (!Privates.empty()) {
4979 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4980 if (NeedsCleanup)
4981 Flags = Flags | DestructorsFlag;
4982 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004983 if (Data.Priority.getInt())
4984 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004985 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004986 Data.Final.getPointer()
4987 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004988 CGF.Builder.getInt32(FinalFlag),
4989 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004990 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004991 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004992 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004993 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4994 getThreadID(CGF, Loc), TaskFlags,
4995 KmpTaskTWithPrivatesTySize, SharedsSize,
4996 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4997 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004998 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004999 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005000 llvm::Value *NewTaskNewTaskTTy =
5001 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5002 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005003 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
5004 KmpTaskTWithPrivatesQTy);
5005 LValue TDBase =
5006 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00005007 // Fill the data in the resulting kmp_task_t record.
5008 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00005009 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005010 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00005011 KmpTaskSharedsPtr =
5012 Address(CGF.EmitLoadOfScalar(
5013 CGF.EmitLValueForField(
5014 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
5015 KmpTaskTShareds)),
5016 Loc),
5017 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00005018 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
5019 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00005020 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005021 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005022 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00005023 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005024 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00005025 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
5026 SharedsTy, SharedsPtrTy, Data, Privates,
5027 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005028 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
5029 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
5030 Result.TaskDupFn = emitTaskDupFunction(
5031 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
5032 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
5033 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005034 }
5035 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00005036 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
5037 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00005038 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00005039 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005040 const RecordDecl *KmpCmplrdataUD =
5041 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00005042 if (NeedsCleanup) {
5043 llvm::Value *DestructorFn = emitDestructorsFunction(
5044 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
5045 KmpTaskTWithPrivatesQTy);
5046 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
5047 LValue DestructorsLV = CGF.EmitLValueForField(
5048 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
5049 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5050 DestructorFn, KmpRoutineEntryPtrTy),
5051 DestructorsLV);
5052 }
5053 // Set priority.
5054 if (Data.Priority.getInt()) {
5055 LValue Data2LV = CGF.EmitLValueForField(
5056 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
5057 LValue PriorityLV = CGF.EmitLValueForField(
5058 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
5059 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
5060 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005061 Result.NewTask = NewTask;
5062 Result.TaskEntry = TaskEntry;
5063 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
5064 Result.TDBase = TDBase;
5065 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
5066 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00005067}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005068
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005069void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
5070 const OMPExecutableDirective &D,
5071 llvm::Value *TaskFunction,
5072 QualType SharedsTy, Address Shareds,
5073 const Expr *IfCond,
5074 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005075 if (!CGF.HaveInsertPoint())
5076 return;
5077
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005078 TaskResultTy Result =
5079 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5080 llvm::Value *NewTask = Result.NewTask;
5081 llvm::Value *TaskEntry = Result.TaskEntry;
5082 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
5083 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005084 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
5085 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005086 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00005087 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005088 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00005089 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005090 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00005091 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005092 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
5093 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005094 QualType FlagsTy =
5095 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005096 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
5097 if (KmpDependInfoTy.isNull()) {
5098 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
5099 KmpDependInfoRD->startDefinition();
5100 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
5101 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
5102 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
5103 KmpDependInfoRD->completeDefinition();
5104 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005105 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005106 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005107 }
John McCall7f416cc2015-09-08 08:05:57 +00005108 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005109 // Define type kmp_depend_info[<Dependences.size()>];
5110 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005111 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005112 ArrayType::Normal, /*IndexTypeQuals=*/0);
5113 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005114 DependenciesArray =
5115 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005116 for (unsigned I = 0; I < NumDependencies; ++I) {
5117 const Expr *E = Data.Dependences[I].second;
5118 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005119 llvm::Value *Size;
5120 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005121 if (const auto *ASE =
5122 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005123 LValue UpAddrLVal =
5124 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5125 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005126 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005127 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005128 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005129 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5130 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005131 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005132 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005133 }
5134 LValue Base = CGF.MakeAddrLValue(
5135 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005136 KmpDependInfoTy);
5137 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005138 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005139 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005140 CGF.EmitStoreOfScalar(
5141 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5142 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005143 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005144 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005145 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5146 CGF.EmitStoreOfScalar(Size, LenLVal);
5147 // deps[i].flags = <Dependences[i].first>;
5148 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005149 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005150 case OMPC_DEPEND_in:
5151 DepKind = DepIn;
5152 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005153 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005154 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005155 case OMPC_DEPEND_inout:
5156 DepKind = DepInOut;
5157 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005158 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005159 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005160 case OMPC_DEPEND_unknown:
5161 llvm_unreachable("Unknown task dependence type");
5162 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005163 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005164 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5165 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5166 FlagsLVal);
5167 }
John McCall7f416cc2015-09-08 08:05:57 +00005168 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5169 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005170 CGF.VoidPtrTy);
5171 }
5172
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005173 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005174 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005175 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5176 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5177 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5178 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005179 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5180 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005181 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5182 llvm::Value *DepTaskArgs[7];
5183 if (NumDependencies) {
5184 DepTaskArgs[0] = UpLoc;
5185 DepTaskArgs[1] = ThreadID;
5186 DepTaskArgs[2] = NewTask;
5187 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5188 DepTaskArgs[4] = DependenciesArray.getPointer();
5189 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5190 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5191 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005192 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5193 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005194 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005195 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005196 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005197 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005198 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5199 }
John McCall7f416cc2015-09-08 08:05:57 +00005200 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005201 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005202 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005203 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005204 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005205 TaskArgs);
5206 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005207 // Check if parent region is untied and build return for untied task;
5208 if (auto *Region =
5209 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5210 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005211 };
John McCall7f416cc2015-09-08 08:05:57 +00005212
5213 llvm::Value *DepWaitTaskArgs[6];
5214 if (NumDependencies) {
5215 DepWaitTaskArgs[0] = UpLoc;
5216 DepWaitTaskArgs[1] = ThreadID;
5217 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5218 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5219 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5220 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5221 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005222 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005223 NumDependencies, &DepWaitTaskArgs,
5224 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005225 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005226 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5227 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5228 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5229 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5230 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005231 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005232 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005233 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005234 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005235 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5236 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005237 Action.Enter(CGF);
5238 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005239 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005240 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005241 };
5242
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005243 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5244 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005245 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5246 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005247 RegionCodeGenTy RCG(CodeGen);
5248 CommonActionTy Action(
5249 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5250 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5251 RCG.setAction(Action);
5252 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005253 };
John McCall7f416cc2015-09-08 08:05:57 +00005254
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005255 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005256 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005257 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005258 RegionCodeGenTy ThenRCG(ThenCodeGen);
5259 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005260 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005261}
5262
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005263void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5264 const OMPLoopDirective &D,
5265 llvm::Value *TaskFunction,
5266 QualType SharedsTy, Address Shareds,
5267 const Expr *IfCond,
5268 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005269 if (!CGF.HaveInsertPoint())
5270 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005271 TaskResultTy Result =
5272 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005273 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005274 // libcall.
5275 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5276 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5277 // sched, kmp_uint64 grainsize, void *task_dup);
5278 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5279 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5280 llvm::Value *IfVal;
5281 if (IfCond) {
5282 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5283 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005284 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005285 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005286 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005287
5288 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005289 Result.TDBase,
5290 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005291 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005292 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5293 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5294 /*IsInitializer=*/true);
5295 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005296 Result.TDBase,
5297 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005298 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005299 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5300 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5301 /*IsInitializer=*/true);
5302 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005303 Result.TDBase,
5304 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005305 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005306 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5307 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5308 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005309 // Store reductions address.
5310 LValue RedLVal = CGF.EmitLValueForField(
5311 Result.TDBase,
5312 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005313 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005314 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005315 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005316 CGF.EmitNullInitialization(RedLVal.getAddress(),
5317 CGF.getContext().VoidPtrTy);
5318 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005319 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005320 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005321 UpLoc,
5322 ThreadID,
5323 Result.NewTask,
5324 IfVal,
5325 LBLVal.getPointer(),
5326 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005327 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataevac6e4de2018-10-24 19:06:37 +00005328 llvm::ConstantInt::getSigned(
5329 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005330 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005331 CGF.IntTy, Data.Schedule.getPointer()
5332 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005333 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005334 Data.Schedule.getPointer()
5335 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005336 /*isSigned=*/false)
5337 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005338 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5339 Result.TaskDupFn, CGF.VoidPtrTy)
5340 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005341 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5342}
5343
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005344/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005345/// array sections) LHS op = RHS.
5346/// \param Type Type of array.
5347/// \param LHSVar Variable on the left side of the reduction operation
5348/// (references element of array in original variable).
5349/// \param RHSVar Variable on the right side of the reduction operation
5350/// (references element of array in original variable).
5351/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5352/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005353static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005354 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5355 const VarDecl *RHSVar,
5356 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5357 const Expr *, const Expr *)> &RedOpGen,
5358 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5359 const Expr *UpExpr = nullptr) {
5360 // Perform element-by-element initialization.
5361 QualType ElementTy;
5362 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5363 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5364
5365 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005366 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5367 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005368
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005369 llvm::Value *RHSBegin = RHSAddr.getPointer();
5370 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005371 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005372 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005373 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005374 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5375 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5376 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005377 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5378 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5379
5380 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005381 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005382 CGF.EmitBlock(BodyBB);
5383
5384 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5385
5386 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5387 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5388 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5389 Address RHSElementCurrent =
5390 Address(RHSElementPHI,
5391 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5392
5393 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5394 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5395 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5396 Address LHSElementCurrent =
5397 Address(LHSElementPHI,
5398 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5399
5400 // Emit copy.
5401 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005402 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5403 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005404 Scope.Privatize();
5405 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5406 Scope.ForceCleanup();
5407
5408 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005409 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005410 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005411 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005412 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5413 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005414 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005415 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5416 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5417 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5418 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5419
5420 // Done.
5421 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5422}
5423
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005424/// Emit reduction combiner. If the combiner is a simple expression emit it as
5425/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5426/// UDR combiner function.
5427static void emitReductionCombiner(CodeGenFunction &CGF,
5428 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005429 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5430 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5431 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005432 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005433 if (const auto *DRD =
5434 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005435 std::pair<llvm::Function *, llvm::Function *> Reduction =
5436 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5437 RValue Func = RValue::get(Reduction.first);
5438 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5439 CGF.EmitIgnoredExpr(ReductionOp);
5440 return;
5441 }
5442 CGF.EmitIgnoredExpr(ReductionOp);
5443}
5444
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005445llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005446 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5447 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5448 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005449 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005450
5451 // void reduction_func(void *LHSArg, void *RHSArg);
5452 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005453 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5454 ImplicitParamDecl::Other);
5455 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5456 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005457 Args.push_back(&LHSArg);
5458 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005459 const auto &CGFI =
5460 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005461 std::string Name = getName({"omp", "reduction", "reduction_func"});
5462 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5463 llvm::GlobalValue::InternalLinkage, Name,
5464 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005465 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005466 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005467 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005468 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005469
5470 // Dst = (void*[n])(LHSArg);
5471 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005472 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5473 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5474 ArgsType), CGF.getPointerAlign());
5475 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5476 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5477 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005478
5479 // ...
5480 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5481 // ...
5482 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005483 auto IPriv = Privates.begin();
5484 unsigned Idx = 0;
5485 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005486 const auto *RHSVar =
5487 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5488 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005489 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005490 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005491 const auto *LHSVar =
5492 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5493 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005494 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005495 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005496 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005497 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005498 // Get array size and emit VLA type.
5499 ++Idx;
5500 Address Elem =
5501 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5502 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005503 const VariableArrayType *VLA =
5504 CGF.getContext().getAsVariableArrayType(PrivTy);
5505 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005506 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005507 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005508 CGF.EmitVariablyModifiedType(PrivTy);
5509 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005510 }
5511 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005512 IPriv = Privates.begin();
5513 auto ILHS = LHSExprs.begin();
5514 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005515 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005516 if ((*IPriv)->getType()->isArrayType()) {
5517 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005518 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5519 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005520 EmitOMPAggregateReduction(
5521 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5522 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5523 emitReductionCombiner(CGF, E);
5524 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005525 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005526 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005527 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005528 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005529 ++IPriv;
5530 ++ILHS;
5531 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005532 }
5533 Scope.ForceCleanup();
5534 CGF.FinishFunction();
5535 return Fn;
5536}
5537
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005538void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5539 const Expr *ReductionOp,
5540 const Expr *PrivateRef,
5541 const DeclRefExpr *LHS,
5542 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005543 if (PrivateRef->getType()->isArrayType()) {
5544 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005545 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5546 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005547 EmitOMPAggregateReduction(
5548 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5549 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5550 emitReductionCombiner(CGF, ReductionOp);
5551 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005552 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005553 // Emit reduction for array subscript or single variable.
5554 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005555 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005556}
5557
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005558void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005559 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005560 ArrayRef<const Expr *> LHSExprs,
5561 ArrayRef<const Expr *> RHSExprs,
5562 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005563 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005564 if (!CGF.HaveInsertPoint())
5565 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005566
5567 bool WithNowait = Options.WithNowait;
5568 bool SimpleReduction = Options.SimpleReduction;
5569
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005570 // Next code should be emitted for reduction:
5571 //
5572 // static kmp_critical_name lock = { 0 };
5573 //
5574 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5575 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5576 // ...
5577 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5578 // *(Type<n>-1*)rhs[<n>-1]);
5579 // }
5580 //
5581 // ...
5582 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5583 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5584 // RedList, reduce_func, &<lock>)) {
5585 // case 1:
5586 // ...
5587 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5588 // ...
5589 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5590 // break;
5591 // case 2:
5592 // ...
5593 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5594 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005595 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005596 // break;
5597 // default:;
5598 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005599 //
5600 // if SimpleReduction is true, only the next code is generated:
5601 // ...
5602 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5603 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005604
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005605 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005606
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005607 if (SimpleReduction) {
5608 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005609 auto IPriv = Privates.begin();
5610 auto ILHS = LHSExprs.begin();
5611 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005612 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005613 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5614 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005615 ++IPriv;
5616 ++ILHS;
5617 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005618 }
5619 return;
5620 }
5621
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005622 // 1. Build a list of reduction variables.
5623 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005624 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005625 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005626 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005627 // Reserve place for array size.
5628 ++Size;
5629 }
5630 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005631 QualType ReductionArrayTy =
5632 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5633 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005634 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005635 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005636 auto IPriv = Privates.begin();
5637 unsigned Idx = 0;
5638 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005639 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005640 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005641 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005642 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005643 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5644 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005645 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005646 // Store array size.
5647 ++Idx;
5648 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5649 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005650 llvm::Value *Size = CGF.Builder.CreateIntCast(
5651 CGF.getVLASize(
5652 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005653 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005654 CGF.SizeTy, /*isSigned=*/false);
5655 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5656 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005657 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005658 }
5659
5660 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005661 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005662 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5663 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005664
5665 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005666 std::string Name = getName({"reduction"});
5667 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005668
5669 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5670 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005671 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5672 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5673 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5674 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005675 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005676 llvm::Value *Args[] = {
5677 IdentTLoc, // ident_t *<loc>
5678 ThreadId, // i32 <gtid>
5679 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5680 ReductionArrayTySize, // size_type sizeof(RedList)
5681 RL, // void *RedList
5682 ReductionFn, // void (*) (void *, void *) <reduce_func>
5683 Lock // kmp_critical_name *&<lock>
5684 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005685 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005686 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5687 : OMPRTL__kmpc_reduce),
5688 Args);
5689
5690 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005691 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5692 llvm::SwitchInst *SwInst =
5693 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005694
5695 // 6. Build case 1:
5696 // ...
5697 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5698 // ...
5699 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5700 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005701 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005702 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5703 CGF.EmitBlock(Case1BB);
5704
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005705 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5706 llvm::Value *EndArgs[] = {
5707 IdentTLoc, // ident_t *<loc>
5708 ThreadId, // i32 <gtid>
5709 Lock // kmp_critical_name *&<lock>
5710 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005711 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5712 CodeGenFunction &CGF, PrePostActionTy &Action) {
5713 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005714 auto IPriv = Privates.begin();
5715 auto ILHS = LHSExprs.begin();
5716 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005717 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005718 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5719 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005720 ++IPriv;
5721 ++ILHS;
5722 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005723 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005724 };
5725 RegionCodeGenTy RCG(CodeGen);
5726 CommonActionTy Action(
5727 nullptr, llvm::None,
5728 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5729 : OMPRTL__kmpc_end_reduce),
5730 EndArgs);
5731 RCG.setAction(Action);
5732 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005733
5734 CGF.EmitBranch(DefaultBB);
5735
5736 // 7. Build case 2:
5737 // ...
5738 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5739 // ...
5740 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005741 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005742 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5743 CGF.EmitBlock(Case2BB);
5744
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005745 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5746 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005747 auto ILHS = LHSExprs.begin();
5748 auto IRHS = RHSExprs.begin();
5749 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005750 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005751 const Expr *XExpr = nullptr;
5752 const Expr *EExpr = nullptr;
5753 const Expr *UpExpr = nullptr;
5754 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005755 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005756 if (BO->getOpcode() == BO_Assign) {
5757 XExpr = BO->getLHS();
5758 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005759 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005760 }
5761 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005762 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005763 if (RHSExpr) {
5764 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005765 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005766 RHSExpr->IgnoreParenImpCasts())) {
5767 // If this is a conditional operator, analyze its condition for
5768 // min/max reduction operator.
5769 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005770 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005771 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005772 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5773 EExpr = BORHS->getRHS();
5774 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005775 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005776 }
5777 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005778 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005779 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005780 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5781 const Expr *EExpr, const Expr *UpExpr) {
5782 LValue X = CGF.EmitLValue(XExpr);
5783 RValue E;
5784 if (EExpr)
5785 E = CGF.EmitAnyExpr(EExpr);
5786 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005787 X, E, BO, /*IsXLHSInRHSPart=*/true,
5788 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005789 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005790 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5791 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005792 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005793 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5794 CGF.emitOMPSimpleStore(
5795 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5796 VD->getType().getNonReferenceType(), Loc);
5797 return LHSTemp;
5798 });
5799 (void)PrivateScope.Privatize();
5800 return CGF.EmitAnyExpr(UpExpr);
5801 });
5802 };
5803 if ((*IPriv)->getType()->isArrayType()) {
5804 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005805 const auto *RHSVar =
5806 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005807 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5808 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005809 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005810 // Emit atomic reduction for array subscript or single variable.
5811 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005812 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005813 } else {
5814 // Emit as a critical region.
5815 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005816 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005817 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005818 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005819 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005820 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005821 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5822 Action.Enter(CGF);
5823 emitReductionCombiner(CGF, E);
5824 },
5825 Loc);
5826 };
5827 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005828 const auto *LHSVar =
5829 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5830 const auto *RHSVar =
5831 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005832 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5833 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005834 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005835 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005836 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005837 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005838 ++ILHS;
5839 ++IRHS;
5840 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005841 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005842 };
5843 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5844 if (!WithNowait) {
5845 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5846 llvm::Value *EndArgs[] = {
5847 IdentTLoc, // ident_t *<loc>
5848 ThreadId, // i32 <gtid>
5849 Lock // kmp_critical_name *&<lock>
5850 };
5851 CommonActionTy Action(nullptr, llvm::None,
5852 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5853 EndArgs);
5854 AtomicRCG.setAction(Action);
5855 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005856 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005857 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005858 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005859
5860 CGF.EmitBranch(DefaultBB);
5861 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5862}
5863
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005864/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005865/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5866static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5867 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005868 SmallString<256> Buffer;
5869 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005870 const clang::DeclRefExpr *DE;
5871 const VarDecl *D = ::getBaseDecl(Ref, DE);
5872 if (!D)
5873 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5874 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005875 std::string Name = CGM.getOpenMPRuntime().getName(
5876 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5877 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005878 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005879 return Out.str();
5880}
5881
5882/// Emits reduction initializer function:
5883/// \code
5884/// void @.red_init(void* %arg) {
5885/// %0 = bitcast void* %arg to <type>*
5886/// store <type> <init>, <type>* %0
5887/// ret void
5888/// }
5889/// \endcode
5890static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5891 SourceLocation Loc,
5892 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005893 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005894 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005895 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5896 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005897 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005898 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005899 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005900 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005901 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005902 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005903 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005904 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005905 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005906 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005907 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005908 Address PrivateAddr = CGF.EmitLoadOfPointer(
5909 CGF.GetAddrOfLocalVar(&Param),
5910 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5911 llvm::Value *Size = nullptr;
5912 // If the size of the reduction item is non-constant, load it from global
5913 // threadprivate variable.
5914 if (RCG.getSizes(N).second) {
5915 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5916 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005917 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005918 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5919 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005920 }
5921 RCG.emitAggregateType(CGF, N, Size);
5922 LValue SharedLVal;
5923 // If initializer uses initializer from declare reduction construct, emit a
5924 // pointer to the address of the original reduction item (reuired by reduction
5925 // initializer)
5926 if (RCG.usesReductionInitializer(N)) {
5927 Address SharedAddr =
5928 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5929 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005930 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005931 SharedAddr = CGF.EmitLoadOfPointer(
5932 SharedAddr,
5933 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005934 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5935 } else {
5936 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5937 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5938 CGM.getContext().VoidPtrTy);
5939 }
5940 // Emit the initializer:
5941 // %0 = bitcast void* %arg to <type>*
5942 // store <type> <init>, <type>* %0
5943 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5944 [](CodeGenFunction &) { return false; });
5945 CGF.FinishFunction();
5946 return Fn;
5947}
5948
5949/// Emits reduction combiner function:
5950/// \code
5951/// void @.red_comb(void* %arg0, void* %arg1) {
5952/// %lhs = bitcast void* %arg0 to <type>*
5953/// %rhs = bitcast void* %arg1 to <type>*
5954/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5955/// store <type> %2, <type>* %lhs
5956/// ret void
5957/// }
5958/// \endcode
5959static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5960 SourceLocation Loc,
5961 ReductionCodeGen &RCG, unsigned N,
5962 const Expr *ReductionOp,
5963 const Expr *LHS, const Expr *RHS,
5964 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005965 ASTContext &C = CGM.getContext();
5966 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5967 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005968 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005969 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5970 C.VoidPtrTy, ImplicitParamDecl::Other);
5971 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5972 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005973 Args.emplace_back(&ParamInOut);
5974 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005975 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005976 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005977 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005978 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005979 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005980 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005981 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005982 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005983 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005984 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005985 llvm::Value *Size = nullptr;
5986 // If the size of the reduction item is non-constant, load it from global
5987 // threadprivate variable.
5988 if (RCG.getSizes(N).second) {
5989 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5990 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005991 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005992 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5993 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005994 }
5995 RCG.emitAggregateType(CGF, N, Size);
5996 // Remap lhs and rhs variables to the addresses of the function arguments.
5997 // %lhs = bitcast void* %arg0 to <type>*
5998 // %rhs = bitcast void* %arg1 to <type>*
5999 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006000 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006001 // Pull out the pointer to the variable.
6002 Address PtrAddr = CGF.EmitLoadOfPointer(
6003 CGF.GetAddrOfLocalVar(&ParamInOut),
6004 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6005 return CGF.Builder.CreateElementBitCast(
6006 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
6007 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006008 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006009 // Pull out the pointer to the variable.
6010 Address PtrAddr = CGF.EmitLoadOfPointer(
6011 CGF.GetAddrOfLocalVar(&ParamIn),
6012 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6013 return CGF.Builder.CreateElementBitCast(
6014 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
6015 });
6016 PrivateScope.Privatize();
6017 // Emit the combiner body:
6018 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
6019 // store <type> %2, <type>* %lhs
6020 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
6021 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
6022 cast<DeclRefExpr>(RHS));
6023 CGF.FinishFunction();
6024 return Fn;
6025}
6026
6027/// Emits reduction finalizer function:
6028/// \code
6029/// void @.red_fini(void* %arg) {
6030/// %0 = bitcast void* %arg to <type>*
6031/// <destroy>(<type>* %0)
6032/// ret void
6033/// }
6034/// \endcode
6035static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
6036 SourceLocation Loc,
6037 ReductionCodeGen &RCG, unsigned N) {
6038 if (!RCG.needCleanups(N))
6039 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006040 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006041 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006042 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
6043 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006044 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006045 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006046 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006047 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00006048 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006049 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006050 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00006051 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00006052 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006053 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006054 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006055 Address PrivateAddr = CGF.EmitLoadOfPointer(
6056 CGF.GetAddrOfLocalVar(&Param),
6057 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6058 llvm::Value *Size = nullptr;
6059 // If the size of the reduction item is non-constant, load it from global
6060 // threadprivate variable.
6061 if (RCG.getSizes(N).second) {
6062 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6063 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006064 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006065 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6066 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006067 }
6068 RCG.emitAggregateType(CGF, N, Size);
6069 // Emit the finalizer body:
6070 // <destroy>(<type>* %0)
6071 RCG.emitCleanups(CGF, N, PrivateAddr);
6072 CGF.FinishFunction();
6073 return Fn;
6074}
6075
6076llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
6077 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
6078 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
6079 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
6080 return nullptr;
6081
6082 // Build typedef struct:
6083 // kmp_task_red_input {
6084 // void *reduce_shar; // shared reduction item
6085 // size_t reduce_size; // size of data item
6086 // void *reduce_init; // data initialization routine
6087 // void *reduce_fini; // data finalization routine
6088 // void *reduce_comb; // data combiner routine
6089 // kmp_task_red_flags_t flags; // flags for additional info from compiler
6090 // } kmp_task_red_input_t;
6091 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006092 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006093 RD->startDefinition();
6094 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6095 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
6096 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6097 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6098 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6099 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6100 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6101 RD->completeDefinition();
6102 QualType RDType = C.getRecordType(RD);
6103 unsigned Size = Data.ReductionVars.size();
6104 llvm::APInt ArraySize(/*numBits=*/64, Size);
6105 QualType ArrayRDType = C.getConstantArrayType(
6106 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6107 // kmp_task_red_input_t .rd_input.[Size];
6108 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6109 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6110 Data.ReductionOps);
6111 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6112 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6113 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6114 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6115 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6116 TaskRedInput.getPointer(), Idxs,
6117 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6118 ".rd_input.gep.");
6119 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6120 // ElemLVal.reduce_shar = &Shareds[Cnt];
6121 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6122 RCG.emitSharedLValue(CGF, Cnt);
6123 llvm::Value *CastedShared =
6124 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6125 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6126 RCG.emitAggregateType(CGF, Cnt);
6127 llvm::Value *SizeValInChars;
6128 llvm::Value *SizeVal;
6129 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6130 // We use delayed creation/initialization for VLAs, array sections and
6131 // custom reduction initializations. It is required because runtime does not
6132 // provide the way to pass the sizes of VLAs/array sections to
6133 // initializer/combiner/finalizer functions and does not pass the pointer to
6134 // original reduction item to the initializer. Instead threadprivate global
6135 // variables are used to store these values and use them in the functions.
6136 bool DelayedCreation = !!SizeVal;
6137 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6138 /*isSigned=*/false);
6139 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6140 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6141 // ElemLVal.reduce_init = init;
6142 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6143 llvm::Value *InitAddr =
6144 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6145 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6146 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6147 // ElemLVal.reduce_fini = fini;
6148 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6149 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6150 llvm::Value *FiniAddr = Fini
6151 ? CGF.EmitCastToVoidPtr(Fini)
6152 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6153 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6154 // ElemLVal.reduce_comb = comb;
6155 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6156 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6157 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6158 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6159 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6160 // ElemLVal.flags = 0;
6161 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6162 if (DelayedCreation) {
6163 CGF.EmitStoreOfScalar(
6164 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6165 FlagsLVal);
6166 } else
6167 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6168 }
6169 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6170 // *data);
6171 llvm::Value *Args[] = {
6172 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6173 /*isSigned=*/true),
6174 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6175 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6176 CGM.VoidPtrTy)};
6177 return CGF.EmitRuntimeCall(
6178 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6179}
6180
6181void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6182 SourceLocation Loc,
6183 ReductionCodeGen &RCG,
6184 unsigned N) {
6185 auto Sizes = RCG.getSizes(N);
6186 // Emit threadprivate global variable if the type is non-constant
6187 // (Sizes.second = nullptr).
6188 if (Sizes.second) {
6189 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6190 /*isSigned=*/false);
6191 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6192 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006193 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006194 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6195 }
6196 // Store address of the original reduction item if custom initializer is used.
6197 if (RCG.usesReductionInitializer(N)) {
6198 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6199 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006200 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006201 CGF.Builder.CreateStore(
6202 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6203 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6204 SharedAddr, /*IsVolatile=*/false);
6205 }
6206}
6207
6208Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6209 SourceLocation Loc,
6210 llvm::Value *ReductionsPtr,
6211 LValue SharedLVal) {
6212 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6213 // *d);
6214 llvm::Value *Args[] = {
6215 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6216 /*isSigned=*/true),
6217 ReductionsPtr,
6218 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6219 CGM.VoidPtrTy)};
6220 return Address(
6221 CGF.EmitRuntimeCall(
6222 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6223 SharedLVal.getAlignment());
6224}
6225
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006226void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6227 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006228 if (!CGF.HaveInsertPoint())
6229 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006230 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6231 // global_tid);
6232 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6233 // Ignore return result until untied tasks are supported.
6234 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006235 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6236 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006237}
6238
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006239void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006240 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006241 const RegionCodeGenTy &CodeGen,
6242 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006243 if (!CGF.HaveInsertPoint())
6244 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006245 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006246 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006247}
6248
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006249namespace {
6250enum RTCancelKind {
6251 CancelNoreq = 0,
6252 CancelParallel = 1,
6253 CancelLoop = 2,
6254 CancelSections = 3,
6255 CancelTaskgroup = 4
6256};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006257} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006258
6259static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6260 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006261 if (CancelRegion == OMPD_parallel)
6262 CancelKind = CancelParallel;
6263 else if (CancelRegion == OMPD_for)
6264 CancelKind = CancelLoop;
6265 else if (CancelRegion == OMPD_sections)
6266 CancelKind = CancelSections;
6267 else {
6268 assert(CancelRegion == OMPD_taskgroup);
6269 CancelKind = CancelTaskgroup;
6270 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006271 return CancelKind;
6272}
6273
6274void CGOpenMPRuntime::emitCancellationPointCall(
6275 CodeGenFunction &CGF, SourceLocation Loc,
6276 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006277 if (!CGF.HaveInsertPoint())
6278 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006279 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6280 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006281 if (auto *OMPRegionInfo =
6282 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006283 // For 'cancellation point taskgroup', the task region info may not have a
6284 // cancel. This may instead happen in another adjacent task.
6285 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006286 llvm::Value *Args[] = {
6287 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6288 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006289 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006290 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006291 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6292 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006293 // exit from construct;
6294 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006295 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6296 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6297 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006298 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6299 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006300 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006301 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006302 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006303 CGF.EmitBranchThroughCleanup(CancelDest);
6304 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6305 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006306 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006307}
6308
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006309void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006310 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006311 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006312 if (!CGF.HaveInsertPoint())
6313 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006314 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6315 // kmp_int32 cncl_kind);
6316 if (auto *OMPRegionInfo =
6317 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006318 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6319 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006320 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006321 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006322 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006323 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6324 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006325 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006326 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006327 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006328 // exit from construct;
6329 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006330 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6331 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6332 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006333 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6334 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006335 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006336 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006337 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6338 CGF.EmitBranchThroughCleanup(CancelDest);
6339 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6340 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006341 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006342 emitOMPIfClause(CGF, IfCond, ThenGen,
6343 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006344 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006345 RegionCodeGenTy ThenRCG(ThenGen);
6346 ThenRCG(CGF);
6347 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006348 }
6349}
Samuel Antaobed3c462015-10-02 16:14:20 +00006350
Samuel Antaoee8fb302016-01-06 13:42:12 +00006351void CGOpenMPRuntime::emitTargetOutlinedFunction(
6352 const OMPExecutableDirective &D, StringRef ParentName,
6353 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006354 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006355 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006356 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6357 IsOffloadEntry, CodeGen);
6358}
6359
6360void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6361 const OMPExecutableDirective &D, StringRef ParentName,
6362 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6363 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006364 // Create a unique name for the entry function using the source location
6365 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006366 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006367 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006368 //
6369 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006370 // mangled name of the function that encloses the target region and BB is the
6371 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006372
6373 unsigned DeviceID;
6374 unsigned FileID;
6375 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006376 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006377 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006378 SmallString<64> EntryFnName;
6379 {
6380 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006381 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6382 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006383 }
6384
Alexey Bataev475a7442018-01-12 19:39:11 +00006385 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006386
Samuel Antaobed3c462015-10-02 16:14:20 +00006387 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006388 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006389 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006390
Samuel Antao6d004262016-06-16 18:39:34 +00006391 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006392
6393 // If this target outline function is not an offload entry, we don't need to
6394 // register it.
6395 if (!IsOffloadEntry)
6396 return;
6397
6398 // The target region ID is used by the runtime library to identify the current
6399 // target region, so it only has to be unique and not necessarily point to
6400 // anything. It could be the pointer to the outlined function that implements
6401 // the target region, but we aren't using that so that the compiler doesn't
6402 // need to keep that, and could therefore inline the host function if proven
6403 // worthwhile during optimization. In the other hand, if emitting code for the
6404 // device, the ID has to be the function address so that it can retrieved from
6405 // the offloading entry and launched by the runtime library. We also mark the
6406 // outlined function to have external linkage in case we are emitting code for
6407 // the device, because these functions will be entry points to the device.
6408
6409 if (CGM.getLangOpts().OpenMPIsDevice) {
6410 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006411 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006412 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006413 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006414 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006415 OutlinedFnID = new llvm::GlobalVariable(
6416 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006417 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006418 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006419 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006420
6421 // Register the information for the entry associated with this target region.
6422 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006423 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006424 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006425}
6426
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006427/// discard all CompoundStmts intervening between two constructs
6428static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006429 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006430 Body = CS->body_front();
6431
6432 return Body;
6433}
6434
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006435/// Emit the number of teams for a target directive. Inspect the num_teams
6436/// clause associated with a teams construct combined or closely nested
6437/// with the target directive.
6438///
6439/// Emit a team of size one for directives such as 'target parallel' that
6440/// have no associated teams construct.
6441///
6442/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006443static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006444emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6445 CodeGenFunction &CGF,
6446 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006447 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6448 "teams directive expected to be "
6449 "emitted only for the host!");
6450
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006451 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006452
6453 // If the target directive is combined with a teams directive:
6454 // Return the value in the num_teams clause, if any.
6455 // Otherwise, return 0 to denote the runtime default.
6456 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6457 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6458 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006459 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6460 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006461 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6462 /*IsSigned=*/true);
6463 }
6464
6465 // The default value is 0.
6466 return Bld.getInt32(0);
6467 }
6468
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006469 // If the target directive is combined with a parallel directive but not a
6470 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006471 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6472 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006473
6474 // If the current target region has a teams region enclosed, we need to get
6475 // the number of teams to pass to the runtime function call. This is done
6476 // by generating the expression in a inlined region. This is required because
6477 // the expression is captured in the enclosing target environment when the
6478 // teams directive is not combined with target.
6479
Alexey Bataev475a7442018-01-12 19:39:11 +00006480 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006481
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006482 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006483 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006484 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006485 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006486 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6487 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6488 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6489 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6490 /*IsSigned=*/true);
6491 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006492
Alexey Bataev50a1c782017-12-01 21:31:08 +00006493 // If we have an enclosed teams directive but no num_teams clause we use
6494 // the default value 0.
6495 return Bld.getInt32(0);
6496 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006497 }
6498
6499 // No teams associated with the directive.
6500 return nullptr;
6501}
6502
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006503/// Emit the number of threads for a target directive. Inspect the
6504/// thread_limit clause associated with a teams construct combined or closely
6505/// nested with the target directive.
6506///
6507/// Emit the num_threads clause for directives such as 'target parallel' that
6508/// have no associated teams construct.
6509///
6510/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006511static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006512emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6513 CodeGenFunction &CGF,
6514 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006515 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6516 "teams directive expected to be "
6517 "emitted only for the host!");
6518
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006519 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006520
6521 //
6522 // If the target directive is combined with a teams directive:
6523 // Return the value in the thread_limit clause, if any.
6524 //
6525 // If the target directive is combined with a parallel directive:
6526 // Return the value in the num_threads clause, if any.
6527 //
6528 // If both clauses are set, select the minimum of the two.
6529 //
6530 // If neither teams or parallel combined directives set the number of threads
6531 // in a team, return 0 to denote the runtime default.
6532 //
6533 // If this is not a teams directive return nullptr.
6534
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006535 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6536 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006537 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6538 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006539 llvm::Value *ThreadLimitVal = nullptr;
6540
6541 if (const auto *ThreadLimitClause =
6542 D.getSingleClause<OMPThreadLimitClause>()) {
6543 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006544 llvm::Value *ThreadLimit =
6545 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6546 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006547 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6548 /*IsSigned=*/true);
6549 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006550
6551 if (const auto *NumThreadsClause =
6552 D.getSingleClause<OMPNumThreadsClause>()) {
6553 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6554 llvm::Value *NumThreads =
6555 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6556 /*IgnoreResultAssign*/ true);
6557 NumThreadsVal =
6558 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6559 }
6560
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006561 // Select the lesser of thread_limit and num_threads.
6562 if (NumThreadsVal)
6563 ThreadLimitVal = ThreadLimitVal
6564 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6565 ThreadLimitVal),
6566 NumThreadsVal, ThreadLimitVal)
6567 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006568
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006569 // Set default value passed to the runtime if either teams or a target
6570 // parallel type directive is found but no clause is specified.
6571 if (!ThreadLimitVal)
6572 ThreadLimitVal = DefaultThreadLimitVal;
6573
6574 return ThreadLimitVal;
6575 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006576
Samuel Antaob68e2db2016-03-03 16:20:23 +00006577 // If the current target region has a teams region enclosed, we need to get
6578 // the thread limit to pass to the runtime function call. This is done
6579 // by generating the expression in a inlined region. This is required because
6580 // the expression is captured in the enclosing target environment when the
6581 // teams directive is not combined with target.
6582
Alexey Bataev475a7442018-01-12 19:39:11 +00006583 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006584
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006585 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006586 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006587 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006588 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006589 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6590 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6591 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6592 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6593 /*IsSigned=*/true);
6594 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006595
Alexey Bataev50a1c782017-12-01 21:31:08 +00006596 // If we have an enclosed teams directive but no thread_limit clause we
6597 // use the default value 0.
6598 return CGF.Builder.getInt32(0);
6599 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006600 }
6601
6602 // No teams associated with the directive.
6603 return nullptr;
6604}
6605
Samuel Antao86ace552016-04-27 22:40:57 +00006606namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006607LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006609// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006610// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6611// It provides a convenient interface to obtain the information and generate
6612// code for that information.
6613class MappableExprsHandler {
6614public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006615 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006616 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006617 enum OpenMPOffloadMappingFlags : uint64_t {
6618 /// No flags
6619 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006620 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006621 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006622 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006623 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006624 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006625 /// if it was already mapped before.
6626 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006627 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006628 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006629 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006630 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006631 /// pointer and the pointee should be mapped.
6632 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006633 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006634 /// passed to the target kernel as an argument.
6635 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006636 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006637 /// in the current position for the data being mapped. Used when we have the
6638 /// use_device_ptr clause.
6639 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006640 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006641 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006642 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006643 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006644 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006645 /// Implicit map
6646 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006647 /// The 16 MSBs of the flags indicate whether the entry is member of some
6648 /// struct/class.
6649 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6650 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006651 };
6652
Samuel Antaocc10b852016-07-28 14:23:26 +00006653 /// Class that associates information with a base pointer to be passed to the
6654 /// runtime library.
6655 class BasePointerInfo {
6656 /// The base pointer.
6657 llvm::Value *Ptr = nullptr;
6658 /// The base declaration that refers to this device pointer, or null if
6659 /// there is none.
6660 const ValueDecl *DevPtrDecl = nullptr;
6661
6662 public:
6663 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6664 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6665 llvm::Value *operator*() const { return Ptr; }
6666 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6667 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6668 };
6669
Alexey Bataevb3638132018-07-19 16:34:13 +00006670 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6671 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6672 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6673
6674 /// Map between a struct and the its lowest & highest elements which have been
6675 /// mapped.
6676 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6677 /// HE(FieldIndex, Pointer)}
6678 struct StructRangeInfoTy {
6679 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6680 0, Address::invalid()};
6681 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6682 0, Address::invalid()};
6683 Address Base = Address::invalid();
6684 };
Samuel Antao86ace552016-04-27 22:40:57 +00006685
6686private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006687 /// Kind that defines how a device pointer has to be returned.
6688 struct MapInfo {
6689 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6690 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
Kelvin Lief579432018-12-18 22:18:41 +00006691 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataevb3638132018-07-19 16:34:13 +00006692 bool ReturnDevicePointer = false;
6693 bool IsImplicit = false;
6694
6695 MapInfo() = default;
6696 MapInfo(
6697 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Kelvin Lief579432018-12-18 22:18:41 +00006698 OpenMPMapClauseKind MapType,
6699 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00006700 bool ReturnDevicePointer, bool IsImplicit)
Kelvin Lief579432018-12-18 22:18:41 +00006701 : Components(Components), MapType(MapType), MapModifiers(MapModifiers),
Alexey Bataevb3638132018-07-19 16:34:13 +00006702 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6703 };
6704
6705 /// If use_device_ptr is used on a pointer which is a struct member and there
6706 /// is no map information about it, then emission of that entry is deferred
6707 /// until the whole struct has been processed.
6708 struct DeferredDevicePtrEntryTy {
6709 const Expr *IE = nullptr;
6710 const ValueDecl *VD = nullptr;
6711
6712 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6713 : IE(IE), VD(VD) {}
6714 };
6715
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006716 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006717 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006718
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006719 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006720 CodeGenFunction &CGF;
6721
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006722 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006723 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6724
Samuel Antao6890b092016-07-28 14:25:09 +00006725 /// Map between device pointer declarations and their expression components.
6726 /// The key value for declarations in 'this' is null.
6727 llvm::DenseMap<
6728 const ValueDecl *,
6729 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6730 DevPointersMap;
6731
Samuel Antao86ace552016-04-27 22:40:57 +00006732 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006733 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006734
6735 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006736 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006737 ExprTy = RefTy->getPointeeType().getCanonicalType();
6738
6739 // Given that an array section is considered a built-in type, we need to
6740 // do the calculation based on the length of the section instead of relying
6741 // on CGF.getTypeSize(E->getType()).
6742 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6743 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6744 OAE->getBase()->IgnoreParenImpCasts())
6745 .getCanonicalType();
6746
6747 // If there is no length associated with the expression, that means we
6748 // are using the whole length of the base.
6749 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6750 return CGF.getTypeSize(BaseTy);
6751
6752 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006753 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006754 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006755 } else {
6756 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006757 assert(ATy && "Expecting array type if not a pointer type.");
6758 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6759 }
6760
6761 // If we don't have a length at this point, that is because we have an
6762 // array section with a single element.
6763 if (!OAE->getLength())
6764 return ElemSize;
6765
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006766 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006767 LengthVal =
6768 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6769 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6770 }
6771 return CGF.getTypeSize(ExprTy);
6772 }
6773
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006774 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006775 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006776 /// map as the first one of a series of maps that relate to the same map
6777 /// expression.
Kelvin Lief579432018-12-18 22:18:41 +00006778 OpenMPOffloadMappingFlags getMapTypeBits(
6779 OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
6780 bool IsImplicit, bool AddPtrFlag, bool AddIsTargetParamFlag) const {
Alexey Bataevb3638132018-07-19 16:34:13 +00006781 OpenMPOffloadMappingFlags Bits =
6782 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006783 switch (MapType) {
6784 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006785 case OMPC_MAP_release:
6786 // alloc and release is the default behavior in the runtime library, i.e.
6787 // if we don't pass any bits alloc/release that is what the runtime is
6788 // going to do. Therefore, we don't need to signal anything for these two
6789 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006790 break;
6791 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006792 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006793 break;
6794 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006795 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006796 break;
6797 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006798 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006799 break;
6800 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006801 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006802 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006803 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006804 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006805 }
6806 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006807 Bits |= OMP_MAP_PTR_AND_OBJ;
6808 if (AddIsTargetParamFlag)
6809 Bits |= OMP_MAP_TARGET_PARAM;
Kelvin Lief579432018-12-18 22:18:41 +00006810 if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_always)
6811 != MapModifiers.end())
Samuel Antao86ace552016-04-27 22:40:57 +00006812 Bits |= OMP_MAP_ALWAYS;
6813 return Bits;
6814 }
6815
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006816 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006817 /// final array section, is one whose length can't be proved to be one.
6818 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006819 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006820
6821 // It is not an array section and therefore not a unity-size one.
6822 if (!OASE)
6823 return false;
6824
6825 // An array section with no colon always refer to a single element.
6826 if (OASE->getColonLoc().isInvalid())
6827 return false;
6828
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006829 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006830
6831 // If we don't have a length we have to check if the array has size 1
6832 // for this dimension. Also, we should always expect a length if the
6833 // base type is pointer.
6834 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006835 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6836 OASE->getBase()->IgnoreParenImpCasts())
6837 .getCanonicalType();
6838 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006839 return ATy->getSize().getSExtValue() != 1;
6840 // If we don't have a constant dimension length, we have to consider
6841 // the current section as having any size, so it is not necessarily
6842 // unitary. If it happen to be unity size, that's user fault.
6843 return true;
6844 }
6845
6846 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +00006847 Expr::EvalResult Result;
6848 if (!Length->EvaluateAsInt(Result, CGF.getContext()))
Samuel Antao86ace552016-04-27 22:40:57 +00006849 return true; // Can have more that size 1.
6850
Fangrui Song407659a2018-11-30 23:41:18 +00006851 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antao86ace552016-04-27 22:40:57 +00006852 return ConstLength.getSExtValue() != 1;
6853 }
6854
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006855 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006856 /// bits for the provided map type, map modifier, and expression components.
6857 /// \a IsFirstComponent should be set to true if the provided set of
6858 /// components is the first associated with a capture.
6859 void generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00006860 OpenMPMapClauseKind MapType,
6861 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Samuel Antao86ace552016-04-27 22:40:57 +00006862 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006863 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006864 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006865 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006866 bool IsImplicit,
6867 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6868 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006869 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006870 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006871 // base pointer, section pointer, size, flags
6872 // (to add to the ones that come from the map type and modifier).
6873 //
6874 // double d;
6875 // int i[100];
6876 // float *p;
6877 //
6878 // struct S1 {
6879 // int i;
6880 // float f[50];
6881 // }
6882 // struct S2 {
6883 // int i;
6884 // float f[50];
6885 // S1 s;
6886 // double *p;
6887 // struct S2 *ps;
6888 // }
6889 // S2 s;
6890 // S2 *ps;
6891 //
6892 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006893 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006894 //
6895 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006896 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006897 //
6898 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006899 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006900 //
6901 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006902 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006903 //
6904 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006905 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006906 //
6907 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006908 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006909 //
6910 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006911 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006912 //
6913 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006914 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006915 //
6916 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006917 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006918 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006919 // map(to: s.p[:22])
6920 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6921 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6922 // &(s.p), &(s.p[0]), 22*sizeof(double),
6923 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6924 // (*) alloc space for struct members, only this is a target parameter
6925 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6926 // optimizes this entry out, same in the examples below)
6927 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006928 //
6929 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006930 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006931 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006932 // map(from: s.ps->s.i)
6933 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6934 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6935 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006936 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006937 // map(to: s.ps->ps)
6938 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6939 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6940 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006941 //
6942 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006943 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6944 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6945 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6946 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006947 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006948 // map(to: s.ps->ps->s.f[:22])
6949 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6950 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6951 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6952 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006953 //
6954 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006955 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006956 //
6957 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006958 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006959 //
6960 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006961 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006962 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006963 // map(from: ps->p)
6964 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006965 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006966 // map(to: ps->p[:22])
6967 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6968 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6969 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006970 //
6971 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006972 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006973 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006974 // map(from: ps->ps->s.i)
6975 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6976 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6977 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006978 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006979 // map(from: ps->ps->ps)
6980 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6981 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6982 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006983 //
6984 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006985 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6986 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6987 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6988 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006989 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006990 // map(to: ps->ps->ps->s.f[:22])
6991 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6992 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6993 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6994 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6995 //
6996 // map(to: s.f[:22]) map(from: s.p[:33])
6997 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
6998 // sizeof(double*) (**), TARGET_PARAM
6999 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
7000 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
7001 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
7002 // (*) allocate contiguous space needed to fit all mapped members even if
7003 // we allocate space for members not mapped (in this example,
7004 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
7005 // them as well because they fall between &s.f[0] and &s.p)
7006 //
7007 // map(from: s.f[:22]) map(to: ps->p[:33])
7008 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
7009 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7010 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
7011 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
7012 // (*) the struct this entry pertains to is the 2nd element in the list of
7013 // arguments, hence MEMBER_OF(2)
7014 //
7015 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
7016 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
7017 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
7018 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
7019 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7020 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
7021 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
7022 // (*) the struct this entry pertains to is the 4th element in the list
7023 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00007024
7025 // Track if the map information being generated is the first for a capture.
7026 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00007027 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00007028
7029 // Scan the components from the base to the complete expression.
7030 auto CI = Components.rbegin();
7031 auto CE = Components.rend();
7032 auto I = CI;
7033
7034 // Track if the map information being generated is the first for a list of
7035 // components.
7036 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007037 Address BP = Address::invalid();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007038 const Expr *AssocExpr = I->getAssociatedExpression();
7039 const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr);
7040 const auto *OASE = dyn_cast<OMPArraySectionExpr>(AssocExpr);
Samuel Antao86ace552016-04-27 22:40:57 +00007041
Patrick Lystere13b1e32019-01-02 19:28:48 +00007042 if (isa<MemberExpr>(AssocExpr)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007043 // The base is the 'this' pointer. The content of the pointer is going
7044 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00007045 BP = CGF.LoadCXXThisAddress();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007046 } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) ||
7047 (OASE &&
7048 isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) {
7049 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007050 } else {
7051 // The base is the reference to the variable.
7052 // BP = &Var.
Patrick Lystere13b1e32019-01-02 19:28:48 +00007053 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00007054 if (const auto *VD =
7055 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
7056 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007057 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007058 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
7059 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007060 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007061 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007062 }
Samuel Antao86ace552016-04-27 22:40:57 +00007063
7064 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00007065 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00007066 // reference. References are ignored for mapping purposes.
7067 QualType Ty =
7068 I->getAssociatedDeclaration()->getType().getNonReferenceType();
7069 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007070 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00007071
7072 // We do not need to generate individual map information for the
7073 // pointer, it can be associated with the combined storage.
7074 ++I;
7075 }
7076 }
7077
Alexey Bataevb3638132018-07-19 16:34:13 +00007078 // Track whether a component of the list should be marked as MEMBER_OF some
7079 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7080 // in a component list should be marked as MEMBER_OF, all subsequent entries
7081 // do not belong to the base struct. E.g.
7082 // struct S2 s;
7083 // s.ps->ps->ps->f[:]
7084 // (1) (2) (3) (4)
7085 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7086 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7087 // is the pointee of ps(2) which is not member of struct s, so it should not
7088 // be marked as such (it is still PTR_AND_OBJ).
7089 // The variable is initialized to false so that PTR_AND_OBJ entries which
7090 // are not struct members are not considered (e.g. array of pointers to
7091 // data).
7092 bool ShouldBeMemberOf = false;
7093
7094 // Variable keeping track of whether or not we have encountered a component
7095 // in the component list which is a member expression. Useful when we have a
7096 // pointer or a final array section, in which case it is the previous
7097 // component in the list which tells us whether we have a member expression.
7098 // E.g. X.f[:]
7099 // While processing the final array section "[:]" it is "f" which tells us
7100 // whether we are dealing with a member of a declared struct.
7101 const MemberExpr *EncounteredME = nullptr;
7102
Samuel Antao86ace552016-04-27 22:40:57 +00007103 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007104 // If the current component is member of a struct (parent struct) mark it.
7105 if (!EncounteredME) {
7106 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
7107 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
7108 // as MEMBER_OF the parent struct.
7109 if (EncounteredME)
7110 ShouldBeMemberOf = true;
7111 }
7112
Samuel Antao86ace552016-04-27 22:40:57 +00007113 auto Next = std::next(I);
7114
7115 // We need to generate the addresses and sizes if this is the last
7116 // component, if the component is a pointer or if it is an array section
7117 // whose length can't be proved to be one. If this is a pointer, it
7118 // becomes the base address for the following components.
7119
7120 // A final array section, is one whose length can't be proved to be one.
7121 bool IsFinalArraySection =
7122 isFinalArraySectionExpression(I->getAssociatedExpression());
7123
7124 // Get information on whether the element is a pointer. Have to do a
7125 // special treatment for array sections given that they are built-in
7126 // types.
7127 const auto *OASE =
7128 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7129 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007130 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7131 .getCanonicalType()
7132 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007133 I->getAssociatedExpression()->getType()->isAnyPointerType();
7134
7135 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007136 // If this is not the last component, we expect the pointer to be
7137 // associated with an array expression or member expression.
7138 assert((Next == CE ||
7139 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7140 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7141 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7142 "Unexpected expression");
7143
Alexey Bataevb3638132018-07-19 16:34:13 +00007144 Address LB =
7145 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007146
Alexey Bataevb3638132018-07-19 16:34:13 +00007147 // If this component is a pointer inside the base struct then we don't
7148 // need to create any entry for it - it will be combined with the object
7149 // it is pointing to into a single PTR_AND_OBJ entry.
7150 bool IsMemberPointer =
7151 IsPointer && EncounteredME &&
7152 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7153 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007154 if (!OverlappedElements.empty()) {
7155 // Handle base element with the info for overlapped elements.
7156 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7157 assert(Next == CE &&
7158 "Expected last element for the overlapped elements.");
7159 assert(!IsPointer &&
7160 "Unexpected base element with the pointer type.");
7161 // Mark the whole struct as the struct that requires allocation on the
7162 // device.
7163 PartialStruct.LowestElem = {0, LB};
7164 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7165 I->getAssociatedExpression()->getType());
7166 Address HB = CGF.Builder.CreateConstGEP(
7167 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7168 CGF.VoidPtrTy),
7169 TypeSize.getQuantity() - 1, CharUnits::One());
7170 PartialStruct.HighestElem = {
7171 std::numeric_limits<decltype(
7172 PartialStruct.HighestElem.first)>::max(),
7173 HB};
7174 PartialStruct.Base = BP;
7175 // Emit data for non-overlapped data.
7176 OpenMPOffloadMappingFlags Flags =
7177 OMP_MAP_MEMBER_OF |
Kelvin Lief579432018-12-18 22:18:41 +00007178 getMapTypeBits(MapType, MapModifiers, IsImplicit,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007179 /*AddPtrFlag=*/false,
7180 /*AddIsTargetParamFlag=*/false);
7181 LB = BP;
7182 llvm::Value *Size = nullptr;
7183 // Do bitcopy of all non-overlapped structure elements.
7184 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7185 Component : OverlappedElements) {
7186 Address ComponentLB = Address::invalid();
7187 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7188 Component) {
7189 if (MC.getAssociatedDeclaration()) {
7190 ComponentLB =
7191 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7192 .getAddress();
7193 Size = CGF.Builder.CreatePtrDiff(
7194 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7195 CGF.EmitCastToVoidPtr(LB.getPointer()));
7196 break;
7197 }
7198 }
7199 BasePointers.push_back(BP.getPointer());
7200 Pointers.push_back(LB.getPointer());
7201 Sizes.push_back(Size);
7202 Types.push_back(Flags);
7203 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1,
7204 CGF.getPointerSize());
7205 }
7206 BasePointers.push_back(BP.getPointer());
7207 Pointers.push_back(LB.getPointer());
7208 Size = CGF.Builder.CreatePtrDiff(
7209 CGF.EmitCastToVoidPtr(
7210 CGF.Builder.CreateConstGEP(HB, 1, CharUnits::One())
7211 .getPointer()),
7212 CGF.EmitCastToVoidPtr(LB.getPointer()));
7213 Sizes.push_back(Size);
7214 Types.push_back(Flags);
7215 break;
7216 }
7217 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007218 if (!IsMemberPointer) {
7219 BasePointers.push_back(BP.getPointer());
7220 Pointers.push_back(LB.getPointer());
7221 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007222
Alexey Bataevb3638132018-07-19 16:34:13 +00007223 // We need to add a pointer flag for each map that comes from the
7224 // same expression except for the first one. We also need to signal
7225 // this map is the first one that relates with the current capture
7226 // (there is a set of entries for each capture).
7227 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
Kelvin Lief579432018-12-18 22:18:41 +00007228 MapType, MapModifiers, IsImplicit,
Alexey Bataevb3638132018-07-19 16:34:13 +00007229 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7230
7231 if (!IsExpressionFirstInfo) {
7232 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7233 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7234 if (IsPointer)
7235 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7236 OMP_MAP_DELETE);
7237
7238 if (ShouldBeMemberOf) {
7239 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7240 // should be later updated with the correct value of MEMBER_OF.
7241 Flags |= OMP_MAP_MEMBER_OF;
7242 // From now on, all subsequent PTR_AND_OBJ entries should not be
7243 // marked as MEMBER_OF.
7244 ShouldBeMemberOf = false;
7245 }
7246 }
7247
7248 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007249 }
7250
Alexey Bataevb3638132018-07-19 16:34:13 +00007251 // If we have encountered a member expression so far, keep track of the
7252 // mapped member. If the parent is "*this", then the value declaration
7253 // is nullptr.
7254 if (EncounteredME) {
7255 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7256 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007257
Alexey Bataevb3638132018-07-19 16:34:13 +00007258 // Update info about the lowest and highest elements for this struct
7259 if (!PartialStruct.Base.isValid()) {
7260 PartialStruct.LowestElem = {FieldIndex, LB};
7261 PartialStruct.HighestElem = {FieldIndex, LB};
7262 PartialStruct.Base = BP;
7263 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7264 PartialStruct.LowestElem = {FieldIndex, LB};
7265 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7266 PartialStruct.HighestElem = {FieldIndex, LB};
7267 }
7268 }
Samuel Antao86ace552016-04-27 22:40:57 +00007269
7270 // If we have a final array section, we are done with this expression.
7271 if (IsFinalArraySection)
7272 break;
7273
7274 // The pointer becomes the base for the next element.
7275 if (Next != CE)
7276 BP = LB;
7277
7278 IsExpressionFirstInfo = false;
7279 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007280 }
7281 }
7282 }
7283
Alexey Bataevb3638132018-07-19 16:34:13 +00007284 /// Return the adjusted map modifiers if the declaration a capture refers to
7285 /// appears in a first-private clause. This is expected to be used only with
7286 /// directives that start with 'target'.
7287 MappableExprsHandler::OpenMPOffloadMappingFlags
7288 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7289 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7290
7291 // A first private variable captured by reference will use only the
7292 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7293 // declaration is known as first-private in this handler.
7294 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
7295 return MappableExprsHandler::OMP_MAP_PRIVATE |
7296 MappableExprsHandler::OMP_MAP_TO;
7297 return MappableExprsHandler::OMP_MAP_TO |
7298 MappableExprsHandler::OMP_MAP_FROM;
7299 }
7300
7301 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7302 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7303 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7304 << 48);
7305 }
7306
7307 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7308 OpenMPOffloadMappingFlags MemberOfFlag) {
7309 // If the entry is PTR_AND_OBJ but has not been marked with the special
7310 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7311 // marked as MEMBER_OF.
7312 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7313 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7314 return;
7315
7316 // Reset the placeholder value to prepare the flag for the assignment of the
7317 // proper MEMBER_OF value.
7318 Flags &= ~OMP_MAP_MEMBER_OF;
7319 Flags |= MemberOfFlag;
7320 }
7321
Alexey Bataeve82445f2018-09-20 13:54:02 +00007322 void getPlainLayout(const CXXRecordDecl *RD,
7323 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7324 bool AsBase) const {
7325 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7326
7327 llvm::StructType *St =
7328 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7329
7330 unsigned NumElements = St->getNumElements();
7331 llvm::SmallVector<
7332 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7333 RecordLayout(NumElements);
7334
7335 // Fill bases.
7336 for (const auto &I : RD->bases()) {
7337 if (I.isVirtual())
7338 continue;
7339 const auto *Base = I.getType()->getAsCXXRecordDecl();
7340 // Ignore empty bases.
7341 if (Base->isEmpty() || CGF.getContext()
7342 .getASTRecordLayout(Base)
7343 .getNonVirtualSize()
7344 .isZero())
7345 continue;
7346
7347 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7348 RecordLayout[FieldIndex] = Base;
7349 }
7350 // Fill in virtual bases.
7351 for (const auto &I : RD->vbases()) {
7352 const auto *Base = I.getType()->getAsCXXRecordDecl();
7353 // Ignore empty bases.
7354 if (Base->isEmpty())
7355 continue;
7356 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7357 if (RecordLayout[FieldIndex])
7358 continue;
7359 RecordLayout[FieldIndex] = Base;
7360 }
7361 // Fill in all the fields.
7362 assert(!RD->isUnion() && "Unexpected union.");
7363 for (const auto *Field : RD->fields()) {
7364 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7365 // will fill in later.)
7366 if (!Field->isBitField()) {
7367 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7368 RecordLayout[FieldIndex] = Field;
7369 }
7370 }
7371 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7372 &Data : RecordLayout) {
7373 if (Data.isNull())
7374 continue;
7375 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7376 getPlainLayout(Base, Layout, /*AsBase=*/true);
7377 else
7378 Layout.push_back(Data.get<const FieldDecl *>());
7379 }
7380 }
7381
Alexey Bataevb3638132018-07-19 16:34:13 +00007382public:
7383 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7384 : CurDir(Dir), CGF(CGF) {
7385 // Extract firstprivate clause information.
7386 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7387 for (const auto *D : C->varlists())
7388 FirstPrivateDecls.insert(
7389 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7390 // Extract device pointer clause information.
7391 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7392 for (auto L : C->component_lists())
7393 DevPointersMap[L.first].push_back(L.second);
7394 }
7395
7396 /// Generate code for the combined entry if we have a partially mapped struct
7397 /// and take care of the mapping flags of the arguments corresponding to
7398 /// individual struct members.
7399 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7400 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7401 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7402 const StructRangeInfoTy &PartialStruct) const {
7403 // Base is the base of the struct
7404 BasePointers.push_back(PartialStruct.Base.getPointer());
7405 // Pointer is the address of the lowest element
7406 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7407 Pointers.push_back(LB);
7408 // Size is (addr of {highest+1} element) - (addr of lowest element)
7409 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7410 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7411 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7412 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7413 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7414 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7415 /*isSinged=*/false);
7416 Sizes.push_back(Size);
7417 // Map type is always TARGET_PARAM
7418 Types.push_back(OMP_MAP_TARGET_PARAM);
7419 // Remove TARGET_PARAM flag from the first element
7420 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7421
7422 // All other current entries will be MEMBER_OF the combined entry
7423 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7424 // 0xFFFF in the MEMBER_OF field).
7425 OpenMPOffloadMappingFlags MemberOfFlag =
7426 getMemberOfFlag(BasePointers.size() - 1);
7427 for (auto &M : CurTypes)
7428 setCorrectMemberOfFlag(M, MemberOfFlag);
7429 }
7430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007431 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007432 /// types for the extracted mappable expressions. Also, for each item that
7433 /// relates with a device pointer, a pair of the relevant declaration and
7434 /// index where it occurs is appended to the device pointers info array.
7435 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007436 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7437 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007438 // We have to process the component lists that relate with the same
7439 // declaration in a single chunk so that we can generate the map flags
7440 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007441 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007442
7443 // Helper function to fill the information map for the different supported
7444 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007445 auto &&InfoGen = [&Info](
7446 const ValueDecl *D,
7447 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
Kelvin Lief579432018-12-18 22:18:41 +00007448 OpenMPMapClauseKind MapType,
7449 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007450 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007451 const ValueDecl *VD =
7452 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Kelvin Lief579432018-12-18 22:18:41 +00007453 Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007454 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007455 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007456
Paul Robinson78fb1322016-08-01 22:12:46 +00007457 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007458 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7459 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007460 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifiers(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007461 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007462 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007463 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7464 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007465 InfoGen(L.first, L.second, OMPC_MAP_to, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007466 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007467 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007468 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7469 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007470 InfoGen(L.first, L.second, OMPC_MAP_from, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007471 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007472 }
Samuel Antao86ace552016-04-27 22:40:57 +00007473
Samuel Antaocc10b852016-07-28 14:23:26 +00007474 // Look at the use_device_ptr clause information and mark the existing map
7475 // entries as such. If there is no map information for an entry in the
7476 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007477 // section. It is the user fault if that was not mapped before. If there is
7478 // no map information and the pointer is a struct member, then we defer the
7479 // emission of that entry until the whole struct has been processed.
7480 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7481 DeferredInfo;
7482
Paul Robinson78fb1322016-08-01 22:12:46 +00007483 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007484 for (const auto *C :
7485 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007486 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007487 assert(!L.second.empty() && "Not expecting empty list of components!");
7488 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7489 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007490 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007491 // If the first component is a member expression, we have to look into
7492 // 'this', which maps to null in the map of map information. Otherwise
7493 // look directly for the information.
7494 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7495
7496 // We potentially have map information for this declaration already.
7497 // Look for the first set of components that refer to it.
7498 if (It != Info.end()) {
7499 auto CI = std::find_if(
7500 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7501 return MI.Components.back().getAssociatedDeclaration() == VD;
7502 });
7503 // If we found a map entry, signal that the pointer has to be returned
7504 // and move on to the next declaration.
7505 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007506 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007507 continue;
7508 }
7509 }
7510
7511 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007512 // size array section - if the pointer is a struct member we defer this
7513 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007514 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007515 if (isa<MemberExpr>(IE)) {
7516 // Insert the pointer into Info to be processed by
7517 // generateInfoForComponentList. Because it is a member pointer
7518 // without a pointee, no entry will be generated for it, therefore
7519 // we need to generate one after the whole struct has been processed.
7520 // Nonetheless, generateInfoForComponentList must be called to take
7521 // the pointer into account for the calculation of the range of the
7522 // partial struct.
Kelvin Lief579432018-12-18 22:18:41 +00007523 InfoGen(nullptr, L.second, OMPC_MAP_unknown, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007524 /*ReturnDevicePointer=*/false, C->isImplicit());
7525 DeferredInfo[nullptr].emplace_back(IE, VD);
7526 } else {
7527 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7528 this->CGF.EmitLValue(IE), IE->getExprLoc());
7529 BasePointers.emplace_back(Ptr, VD);
7530 Pointers.push_back(Ptr);
7531 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7532 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7533 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007534 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007535 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007536
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007537 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007538 // We need to know when we generate information for the first component
7539 // associated with a capture, because the mapping flags depend on it.
7540 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007541
7542 // Temporary versions of arrays
7543 MapBaseValuesArrayTy CurBasePointers;
7544 MapValuesArrayTy CurPointers;
7545 MapValuesArrayTy CurSizes;
7546 MapFlagsArrayTy CurTypes;
7547 StructRangeInfoTy PartialStruct;
7548
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007549 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007550 assert(!L.Components.empty() &&
7551 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007552
7553 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007554 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007555 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007556 this->generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007557 L.MapType, L.MapModifiers, L.Components, CurBasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007558 CurPointers, CurSizes, CurTypes, PartialStruct,
7559 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007560
7561 // If this entry relates with a device pointer, set the relevant
7562 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007563 if (L.ReturnDevicePointer) {
7564 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007565 "Unexpected number of mapped base pointers.");
7566
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007567 const ValueDecl *RelevantVD =
7568 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007569 assert(RelevantVD &&
7570 "No relevant declaration related with device pointer??");
7571
Alexey Bataevb3638132018-07-19 16:34:13 +00007572 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7573 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007574 }
Samuel Antao86ace552016-04-27 22:40:57 +00007575 IsFirstComponentList = false;
7576 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007577
7578 // Append any pending zero-length pointers which are struct members and
7579 // used with use_device_ptr.
7580 auto CI = DeferredInfo.find(M.first);
7581 if (CI != DeferredInfo.end()) {
7582 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7583 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7584 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7585 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7586 CurBasePointers.emplace_back(BasePtr, L.VD);
7587 CurPointers.push_back(Ptr);
7588 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7589 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7590 // value MEMBER_OF=FFFF so that the entry is later updated with the
7591 // correct value of MEMBER_OF.
7592 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7593 OMP_MAP_MEMBER_OF);
7594 }
7595 }
7596
7597 // If there is an entry in PartialStruct it means we have a struct with
7598 // individual members mapped. Emit an extra combined entry.
7599 if (PartialStruct.Base.isValid())
7600 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7601 PartialStruct);
7602
7603 // We need to append the results of this capture to what we already have.
7604 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7605 Pointers.append(CurPointers.begin(), CurPointers.end());
7606 Sizes.append(CurSizes.begin(), CurSizes.end());
7607 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007608 }
7609 }
7610
Alexey Bataev60705422018-10-30 15:50:12 +00007611 /// Emit capture info for lambdas for variables captured by reference.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007612 void generateInfoForLambdaCaptures(
7613 const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
7614 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7615 MapFlagsArrayTy &Types,
7616 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007617 const auto *RD = VD->getType()
7618 .getCanonicalType()
7619 .getNonReferenceType()
7620 ->getAsCXXRecordDecl();
7621 if (!RD || !RD->isLambda())
7622 return;
7623 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
7624 LValue VDLVal = CGF.MakeAddrLValue(
7625 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
7626 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
7627 FieldDecl *ThisCapture = nullptr;
7628 RD->getCaptureFields(Captures, ThisCapture);
7629 if (ThisCapture) {
7630 LValue ThisLVal =
7631 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007632 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
7633 LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
7634 BasePointers.push_back(ThisLVal.getPointer());
7635 Pointers.push_back(ThisLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007636 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007637 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007638 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7639 }
7640 for (const LambdaCapture &LC : RD->captures()) {
7641 if (LC.getCaptureKind() != LCK_ByRef)
7642 continue;
7643 const VarDecl *VD = LC.getCapturedVar();
7644 auto It = Captures.find(VD);
7645 assert(It != Captures.end() && "Found lambda capture without field.");
7646 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007647 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
7648 LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
7649 BasePointers.push_back(VarLVal.getPointer());
7650 Pointers.push_back(VarLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007651 Sizes.push_back(CGF.getTypeSize(
7652 VD->getType().getCanonicalType().getNonReferenceType()));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007653 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007654 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7655 }
7656 }
7657
7658 /// Set correct indices for lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007659 void adjustMemberOfForLambdaCaptures(
7660 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
7661 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
7662 MapFlagsArrayTy &Types) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007663 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
7664 // Set correct member_of idx for all implicit lambda captures.
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007665 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007666 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
7667 continue;
Alexey Bataev969dbc02018-11-08 15:47:39 +00007668 llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
7669 assert(BasePtr && "Unable to find base lambda address.");
Alexey Bataev60705422018-10-30 15:50:12 +00007670 int TgtIdx = -1;
7671 for (unsigned J = I; J > 0; --J) {
7672 unsigned Idx = J - 1;
7673 if (Pointers[Idx] != BasePtr)
7674 continue;
7675 TgtIdx = Idx;
7676 break;
7677 }
7678 assert(TgtIdx != -1 && "Unable to find parent lambda.");
7679 // All other current entries will be MEMBER_OF the combined entry
7680 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7681 // 0xFFFF in the MEMBER_OF field).
7682 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
7683 setCorrectMemberOfFlag(Types[I], MemberOfFlag);
7684 }
7685 }
7686
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007687 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007688 /// associated to a given capture.
7689 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007690 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007691 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007692 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007693 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7694 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007695 assert(!Cap->capturesVariableArrayType() &&
7696 "Not expecting to generate map info for a variable array type!");
7697
Samuel Antao6890b092016-07-28 14:25:09 +00007698 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007699 const ValueDecl *VD = Cap->capturesThis()
7700 ? nullptr
7701 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007702
Samuel Antao6890b092016-07-28 14:25:09 +00007703 // If this declaration appears in a is_device_ptr clause we just have to
7704 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007705 // pass its value.
7706 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007707 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007708 Pointers.push_back(Arg);
7709 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007710 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007711 return;
7712 }
7713
Alexey Bataeve82445f2018-09-20 13:54:02 +00007714 using MapData =
7715 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
Kelvin Lief579432018-12-18 22:18:41 +00007716 OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>, bool>;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007717 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007718 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007719 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007720 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007721 assert(L.first == VD &&
7722 "We got information for the wrong declaration??");
7723 assert(!L.second.empty() &&
7724 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007725 DeclComponentLists.emplace_back(L.second, C->getMapType(),
Kelvin Lief579432018-12-18 22:18:41 +00007726 C->getMapTypeModifiers(),
Alexey Bataeve82445f2018-09-20 13:54:02 +00007727 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007728 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007729 }
7730
7731 // Find overlapping elements (including the offset from the base element).
7732 llvm::SmallDenseMap<
7733 const MapData *,
7734 llvm::SmallVector<
7735 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7736 4>
7737 OverlappedData;
7738 size_t Count = 0;
7739 for (const MapData &L : DeclComponentLists) {
7740 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7741 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007742 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007743 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007744 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007745 ++Count;
7746 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7747 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
Kelvin Lief579432018-12-18 22:18:41 +00007748 std::tie(Components1, MapType, MapModifiers, IsImplicit) = L1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007749 auto CI = Components.rbegin();
7750 auto CE = Components.rend();
7751 auto SI = Components1.rbegin();
7752 auto SE = Components1.rend();
7753 for (; CI != CE && SI != SE; ++CI, ++SI) {
7754 if (CI->getAssociatedExpression()->getStmtClass() !=
7755 SI->getAssociatedExpression()->getStmtClass())
7756 break;
7757 // Are we dealing with different variables/fields?
7758 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7759 break;
7760 }
7761 // Found overlapping if, at least for one component, reached the head of
7762 // the components list.
7763 if (CI == CE || SI == SE) {
7764 assert((CI != CE || SI != SE) &&
7765 "Unexpected full match of the mapping components.");
7766 const MapData &BaseData = CI == CE ? L : L1;
7767 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7768 SI == SE ? Components : Components1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007769 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7770 OverlappedElements.getSecond().push_back(SubData);
7771 }
7772 }
7773 }
7774 // Sort the overlapped elements for each item.
7775 llvm::SmallVector<const FieldDecl *, 4> Layout;
7776 if (!OverlappedData.empty()) {
7777 if (const auto *CRD =
7778 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7779 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7780 else {
7781 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7782 Layout.append(RD->field_begin(), RD->field_end());
7783 }
7784 }
7785 for (auto &Pair : OverlappedData) {
7786 llvm::sort(
7787 Pair.getSecond(),
7788 [&Layout](
7789 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7790 OMPClauseMappableExprCommon::MappableExprComponentListRef
7791 Second) {
7792 auto CI = First.rbegin();
7793 auto CE = First.rend();
7794 auto SI = Second.rbegin();
7795 auto SE = Second.rend();
7796 for (; CI != CE && SI != SE; ++CI, ++SI) {
7797 if (CI->getAssociatedExpression()->getStmtClass() !=
7798 SI->getAssociatedExpression()->getStmtClass())
7799 break;
7800 // Are we dealing with different variables/fields?
7801 if (CI->getAssociatedDeclaration() !=
7802 SI->getAssociatedDeclaration())
7803 break;
7804 }
Richard Trieu5061e832018-09-21 21:20:33 +00007805
7806 // Lists contain the same elements.
7807 if (CI == CE && SI == SE)
7808 return false;
7809
7810 // List with less elements is less than list with more elements.
7811 if (CI == CE || SI == SE)
7812 return CI == CE;
7813
Alexey Bataeve82445f2018-09-20 13:54:02 +00007814 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7815 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7816 if (FD1->getParent() == FD2->getParent())
7817 return FD1->getFieldIndex() < FD2->getFieldIndex();
7818 const auto It =
7819 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7820 return FD == FD1 || FD == FD2;
7821 });
7822 return *It == FD1;
7823 });
7824 }
7825
7826 // Associated with a capture, because the mapping flags depend on it.
7827 // Go through all of the elements with the overlapped elements.
7828 for (const auto &Pair : OverlappedData) {
7829 const MapData &L = *Pair.getFirst();
7830 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7831 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007832 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007833 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007834 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007835 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7836 OverlappedComponents = Pair.getSecond();
7837 bool IsFirstComponentList = true;
Kelvin Lief579432018-12-18 22:18:41 +00007838 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007839 BasePointers, Pointers, Sizes, Types,
7840 PartialStruct, IsFirstComponentList,
7841 IsImplicit, OverlappedComponents);
7842 }
7843 // Go through other elements without overlapped elements.
7844 bool IsFirstComponentList = OverlappedData.empty();
7845 for (const MapData &L : DeclComponentLists) {
7846 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7847 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007848 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007849 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007850 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007851 auto It = OverlappedData.find(&L);
7852 if (It == OverlappedData.end())
Kelvin Lief579432018-12-18 22:18:41 +00007853 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007854 BasePointers, Pointers, Sizes, Types,
7855 PartialStruct, IsFirstComponentList,
7856 IsImplicit);
7857 IsFirstComponentList = false;
7858 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007859 }
Samuel Antao86ace552016-04-27 22:40:57 +00007860
Alexey Bataevb3638132018-07-19 16:34:13 +00007861 /// Generate the base pointers, section pointers, sizes and map types
7862 /// associated with the declare target link variables.
7863 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7864 MapValuesArrayTy &Pointers,
7865 MapValuesArrayTy &Sizes,
7866 MapFlagsArrayTy &Types) const {
7867 // Map other list items in the map clause which are not captured variables
7868 // but "declare target link" global variables.,
7869 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7870 for (const auto &L : C->component_lists()) {
7871 if (!L.first)
7872 continue;
7873 const auto *VD = dyn_cast<VarDecl>(L.first);
7874 if (!VD)
7875 continue;
7876 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007877 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007878 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7879 continue;
7880 StructRangeInfoTy PartialStruct;
7881 generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007882 C->getMapType(), C->getMapTypeModifiers(), L.second, BasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007883 Pointers, Sizes, Types, PartialStruct,
7884 /*IsFirstComponentList=*/true, C->isImplicit());
7885 assert(!PartialStruct.Base.isValid() &&
7886 "No partial structs for declare target link expected.");
7887 }
7888 }
Samuel Antao86ace552016-04-27 22:40:57 +00007889 }
Samuel Antaod486f842016-05-26 16:53:38 +00007890
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007891 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007892 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007893 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7894 const FieldDecl &RI, llvm::Value *CV,
7895 MapBaseValuesArrayTy &CurBasePointers,
7896 MapValuesArrayTy &CurPointers,
7897 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007898 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007899 // Do the default mapping.
7900 if (CI.capturesThis()) {
7901 CurBasePointers.push_back(CV);
7902 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007903 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007904 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7905 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007906 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007907 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007908 CurBasePointers.push_back(CV);
7909 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007910 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007911 // We have to signal to the runtime captures passed by value that are
7912 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007913 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007914 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7915 } else {
7916 // Pointers are implicitly mapped with a zero size and no flags
7917 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007918 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007919 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7920 }
7921 } else {
7922 assert(CI.capturesVariable() && "Expected captured reference.");
7923 CurBasePointers.push_back(CV);
7924 CurPointers.push_back(CV);
7925
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007926 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007927 QualType ElementType = PtrTy->getPointeeType();
7928 CurSizes.push_back(CGF.getTypeSize(ElementType));
7929 // The default map type for a scalar/complex type is 'to' because by
7930 // default the value doesn't have to be retrieved. For an aggregate
7931 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007932 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Samuel Antaod486f842016-05-26 16:53:38 +00007933 }
George Rokos065755d2017-11-07 18:27:04 +00007934 // Every default map produces a single argument which is a target parameter.
7935 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007936
7937 // Add flag stating this is an implicit map.
7938 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007939 }
Samuel Antao86ace552016-04-27 22:40:57 +00007940};
Samuel Antaodf158d52016-04-27 22:58:19 +00007941
7942enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007943 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007944 /// from environment variables in the spec.
7945 OMP_DEVICEID_UNDEF = -1,
7946};
7947} // anonymous namespace
7948
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007949/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007950/// offloading runtime library. If there is no map or capture information,
7951/// return nullptr by reference.
7952static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007953emitOffloadingArrays(CodeGenFunction &CGF,
7954 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007955 MappableExprsHandler::MapValuesArrayTy &Pointers,
7956 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007957 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7958 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007959 CodeGenModule &CGM = CGF.CGM;
7960 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007961
Samuel Antaocc10b852016-07-28 14:23:26 +00007962 // Reset the array information.
7963 Info.clearArrayInfo();
7964 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007965
Samuel Antaocc10b852016-07-28 14:23:26 +00007966 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007967 // Detect if we have any capture size requiring runtime evaluation of the
7968 // size so that a constant array could be eventually used.
7969 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007970 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007971 if (!isa<llvm::Constant>(S)) {
7972 hasRuntimeEvaluationCaptureSize = true;
7973 break;
7974 }
7975
Samuel Antaocc10b852016-07-28 14:23:26 +00007976 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007977 QualType PointerArrayType =
7978 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7979 /*IndexTypeQuals=*/0);
7980
Samuel Antaocc10b852016-07-28 14:23:26 +00007981 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007982 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007983 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007984 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7985
7986 // If we don't have any VLA types or other types that require runtime
7987 // evaluation, we can use a constant array for the map sizes, otherwise we
7988 // need to fill up the arrays as we do for the pointers.
7989 if (hasRuntimeEvaluationCaptureSize) {
7990 QualType SizeArrayType = Ctx.getConstantArrayType(
7991 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7992 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007993 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007994 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7995 } else {
7996 // We expect all the sizes to be constant, so we collect them to create
7997 // a constant array.
7998 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007999 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00008000 ConstSizes.push_back(cast<llvm::Constant>(S));
8001
8002 auto *SizesArrayInit = llvm::ConstantArray::get(
8003 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008004 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008005 auto *SizesArrayGbl = new llvm::GlobalVariable(
8006 CGM.getModule(), SizesArrayInit->getType(),
8007 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008008 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008009 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008010 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008011 }
8012
8013 // The map types are always constant so we don't need to generate code to
8014 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00008015 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
8016 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00008017 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00008018 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008019 std::string MaptypesName =
8020 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008021 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
8022 CGM.getModule(), MapTypesArrayInit->getType(),
8023 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008024 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008025 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008026 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008027
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008028 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
8029 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008030 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008031 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008032 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008033 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8034 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008035 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8036 CGF.Builder.CreateStore(BPVal, BPAddr);
8037
Samuel Antaocc10b852016-07-28 14:23:26 +00008038 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008039 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00008040 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00008041
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008042 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008043 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008044 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008045 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008046 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8047 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008048 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8049 CGF.Builder.CreateStore(PVal, PAddr);
8050
8051 if (hasRuntimeEvaluationCaptureSize) {
8052 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008053 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
8054 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008055 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008056 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00008057 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
8058 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008059 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00008060 SAddr);
8061 }
8062 }
8063 }
8064}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008065/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00008066/// arrays of pointers, sizes and map types.
8067static void emitOffloadingArraysArgument(
8068 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
8069 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008070 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008071 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00008072 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008073 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008074 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8075 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008076 /*Idx0=*/0, /*Idx1=*/0);
8077 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008078 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8079 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008080 /*Idx0=*/0,
8081 /*Idx1=*/0);
8082 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008083 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008084 /*Idx0=*/0, /*Idx1=*/0);
8085 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00008086 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00008087 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008088 /*Idx0=*/0,
8089 /*Idx1=*/0);
8090 } else {
8091 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8092 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8093 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
8094 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00008095 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00008096 }
Samuel Antao86ace552016-04-27 22:40:57 +00008097}
8098
Alexey Bataev7bb33532019-01-07 21:30:43 +00008099/// Checks if the expression is constant or does not have non-trivial function
8100/// calls.
8101static bool isTrivial(ASTContext &Ctx, const Expr * E) {
8102 // We can skip constant expressions.
8103 // We can skip expressions with trivial calls or simple expressions.
8104 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
8105 !E->hasNonTrivialCall(Ctx)) &&
8106 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
8107}
8108
8109/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
8110/// iff there is only one that is not evaluatable at the compile time.
8111static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
8112 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
8113 const Stmt *Child = nullptr;
8114 for (const Stmt *S : C->body()) {
8115 if (const auto *E = dyn_cast<Expr>(S)) {
8116 if (isTrivial(Ctx, E))
8117 continue;
8118 }
8119 // Some of the statements can be ignored.
8120 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
8121 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
8122 continue;
8123 // Analyze declarations.
8124 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
8125 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
8126 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
8127 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
8128 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
8129 isa<UsingDirectiveDecl>(D) ||
8130 isa<OMPDeclareReductionDecl>(D) ||
8131 isa<OMPThreadPrivateDecl>(D))
8132 return true;
8133 const auto *VD = dyn_cast<VarDecl>(D);
8134 if (!VD)
8135 return false;
8136 return VD->isConstexpr() ||
8137 ((VD->getType().isTrivialType(Ctx) ||
8138 VD->getType()->isReferenceType()) &&
8139 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
8140 }))
8141 continue;
8142 }
8143 // Found multiple children - cannot get the one child only.
8144 if (Child)
8145 return Body;
8146 Child = S;
8147 }
8148 if (Child)
8149 return Child;
8150 }
8151 return Body;
8152}
8153
8154/// Check for inner distribute directive.
8155static const OMPExecutableDirective *
8156getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) {
8157 const auto *CS = D.getInnermostCapturedStmt();
8158 const auto *Body =
8159 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
8160 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
8161
8162 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8163 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
8164 switch (D.getDirectiveKind()) {
8165 case OMPD_target:
8166 if (isOpenMPDistributeDirective(DKind))
8167 return NestedDir;
8168 if (DKind == OMPD_teams) {
8169 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
8170 /*IgnoreCaptured=*/true);
8171 if (!Body)
8172 return nullptr;
8173 ChildStmt = getSingleCompoundChild(Ctx, Body);
8174 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8175 DKind = NND->getDirectiveKind();
8176 if (isOpenMPDistributeDirective(DKind))
8177 return NND;
8178 }
8179 }
8180 return nullptr;
8181 case OMPD_target_teams:
8182 if (isOpenMPDistributeDirective(DKind))
8183 return NestedDir;
8184 return nullptr;
8185 case OMPD_target_parallel:
8186 case OMPD_target_simd:
8187 case OMPD_target_parallel_for:
8188 case OMPD_target_parallel_for_simd:
8189 return nullptr;
8190 case OMPD_target_teams_distribute:
8191 case OMPD_target_teams_distribute_simd:
8192 case OMPD_target_teams_distribute_parallel_for:
8193 case OMPD_target_teams_distribute_parallel_for_simd:
8194 case OMPD_parallel:
8195 case OMPD_for:
8196 case OMPD_parallel_for:
8197 case OMPD_parallel_sections:
8198 case OMPD_for_simd:
8199 case OMPD_parallel_for_simd:
8200 case OMPD_cancel:
8201 case OMPD_cancellation_point:
8202 case OMPD_ordered:
8203 case OMPD_threadprivate:
8204 case OMPD_task:
8205 case OMPD_simd:
8206 case OMPD_sections:
8207 case OMPD_section:
8208 case OMPD_single:
8209 case OMPD_master:
8210 case OMPD_critical:
8211 case OMPD_taskyield:
8212 case OMPD_barrier:
8213 case OMPD_taskwait:
8214 case OMPD_taskgroup:
8215 case OMPD_atomic:
8216 case OMPD_flush:
8217 case OMPD_teams:
8218 case OMPD_target_data:
8219 case OMPD_target_exit_data:
8220 case OMPD_target_enter_data:
8221 case OMPD_distribute:
8222 case OMPD_distribute_simd:
8223 case OMPD_distribute_parallel_for:
8224 case OMPD_distribute_parallel_for_simd:
8225 case OMPD_teams_distribute:
8226 case OMPD_teams_distribute_simd:
8227 case OMPD_teams_distribute_parallel_for:
8228 case OMPD_teams_distribute_parallel_for_simd:
8229 case OMPD_target_update:
8230 case OMPD_declare_simd:
8231 case OMPD_declare_target:
8232 case OMPD_end_declare_target:
8233 case OMPD_declare_reduction:
8234 case OMPD_taskloop:
8235 case OMPD_taskloop_simd:
8236 case OMPD_requires:
8237 case OMPD_unknown:
8238 llvm_unreachable("Unexpected directive.");
8239 }
8240 }
8241
8242 return nullptr;
8243}
8244
8245void CGOpenMPRuntime::emitTargetNumIterationsCall(
8246 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *Device,
8247 const llvm::function_ref<llvm::Value *(
8248 CodeGenFunction &CGF, const OMPLoopDirective &D)> &SizeEmitter) {
8249 OpenMPDirectiveKind Kind = D.getDirectiveKind();
8250 const OMPExecutableDirective *TD = &D;
8251 // Get nested teams distribute kind directive, if any.
8252 if (!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind))
8253 TD = getNestedDistributeDirective(CGM.getContext(), D);
8254 if (!TD)
8255 return;
8256 const auto *LD = cast<OMPLoopDirective>(TD);
8257 auto &&CodeGen = [LD, &Device, &SizeEmitter, this](CodeGenFunction &CGF,
8258 PrePostActionTy &) {
8259 llvm::Value *NumIterations = SizeEmitter(CGF, *LD);
8260
8261 // Emit device ID if any.
8262 llvm::Value *DeviceID;
8263 if (Device)
8264 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
8265 CGF.Int64Ty, /*isSigned=*/true);
8266 else
8267 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8268
8269 llvm::Value *Args[] = {DeviceID, NumIterations};
8270 CGF.EmitRuntimeCall(
8271 createRuntimeFunction(OMPRTL__kmpc_push_target_tripcount), Args);
8272 };
8273 emitInlinedDirective(CGF, OMPD_unknown, CodeGen);
8274}
8275
Samuel Antaobed3c462015-10-02 16:14:20 +00008276void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
8277 const OMPExecutableDirective &D,
8278 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00008279 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008280 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00008281 if (!CGF.HaveInsertPoint())
8282 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00008283
Samuel Antaoee8fb302016-01-06 13:42:12 +00008284 assert(OutlinedFn && "Invalid outlined function!");
8285
Alexey Bataev8451efa2018-01-15 19:06:12 +00008286 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
8287 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00008288 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008289 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
8290 PrePostActionTy &) {
8291 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8292 };
8293 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00008294
Alexey Bataev8451efa2018-01-15 19:06:12 +00008295 CodeGenFunction::OMPTargetDataInfo InputInfo;
8296 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00008297 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008298 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
8299 &MapTypesArray, &CS, RequiresOuterTask,
8300 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008301 // On top of the arrays that were filled up, the target offloading call
8302 // takes as arguments the device id as well as the host pointer. The host
8303 // pointer is used by the runtime library to identify the current target
8304 // region, so it only has to be unique and not necessarily point to
8305 // anything. It could be the pointer to the outlined function that
8306 // implements the target region, but we aren't using that so that the
8307 // compiler doesn't need to keep that, and could therefore inline the host
8308 // function if proven worthwhile during optimization.
8309
Samuel Antaoee8fb302016-01-06 13:42:12 +00008310 // From this point on, we need to have an ID of the target region defined.
8311 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00008312
8313 // Emit device ID if any.
8314 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00008315 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008316 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008317 CGF.Int64Ty, /*isSigned=*/true);
8318 } else {
8319 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8320 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008321
Samuel Antaodf158d52016-04-27 22:58:19 +00008322 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008323 llvm::Value *PointerNum =
8324 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00008325
Samuel Antaob68e2db2016-03-03 16:20:23 +00008326 // Return value of the runtime offloading call.
8327 llvm::Value *Return;
8328
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008329 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
8330 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008331
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008332 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008333 // The target region is an outlined function launched by the runtime
8334 // via calls __tgt_target() or __tgt_target_teams().
8335 //
8336 // __tgt_target() launches a target region with one team and one thread,
8337 // executing a serial region. This master thread may in turn launch
8338 // more threads within its team upon encountering a parallel region,
8339 // however, no additional teams can be launched on the device.
8340 //
8341 // __tgt_target_teams() launches a target region with one or more teams,
8342 // each with one or more threads. This call is required for target
8343 // constructs such as:
8344 // 'target teams'
8345 // 'target' / 'teams'
8346 // 'target teams distribute parallel for'
8347 // 'target parallel'
8348 // and so on.
8349 //
8350 // Note that on the host and CPU targets, the runtime implementation of
8351 // these calls simply call the outlined function without forking threads.
8352 // The outlined functions themselves have runtime calls to
8353 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
8354 // the compiler in emitTeamsCall() and emitParallelCall().
8355 //
8356 // In contrast, on the NVPTX target, the implementation of
8357 // __tgt_target_teams() launches a GPU kernel with the requested number
8358 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00008359 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008360 // If we have NumTeams defined this means that we have an enclosed teams
8361 // region. Therefore we also expect to have NumThreads defined. These two
8362 // values should be defined in the presence of a teams directive,
8363 // regardless of having any clauses associated. If the user is using teams
8364 // but no clauses, these two values will be the default that should be
8365 // passed to the runtime library - a 32-bit integer with the value zero.
8366 assert(NumThreads && "Thread limit expression should be available along "
8367 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00008368 llvm::Value *OffloadingArgs[] = {DeviceID,
8369 OutlinedFnID,
8370 PointerNum,
8371 InputInfo.BasePointersArray.getPointer(),
8372 InputInfo.PointersArray.getPointer(),
8373 InputInfo.SizesArray.getPointer(),
8374 MapTypesArray,
8375 NumTeams,
8376 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00008377 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008378 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8379 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008380 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008381 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008382 llvm::Value *OffloadingArgs[] = {DeviceID,
8383 OutlinedFnID,
8384 PointerNum,
8385 InputInfo.BasePointersArray.getPointer(),
8386 InputInfo.PointersArray.getPointer(),
8387 InputInfo.SizesArray.getPointer(),
8388 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008389 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008390 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8391 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008392 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008393 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008394
Alexey Bataev2a007e02017-10-02 14:20:58 +00008395 // Check the error code and execute the host version if required.
8396 llvm::BasicBlock *OffloadFailedBlock =
8397 CGF.createBasicBlock("omp_offload.failed");
8398 llvm::BasicBlock *OffloadContBlock =
8399 CGF.createBasicBlock("omp_offload.cont");
8400 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8401 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8402
8403 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008404 if (RequiresOuterTask) {
8405 CapturedVars.clear();
8406 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8407 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008408 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008409 CGF.EmitBranch(OffloadContBlock);
8410
8411 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008412 };
8413
Samuel Antaoee8fb302016-01-06 13:42:12 +00008414 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008415 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8416 RequiresOuterTask](CodeGenFunction &CGF,
8417 PrePostActionTy &) {
8418 if (RequiresOuterTask) {
8419 CapturedVars.clear();
8420 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8421 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008422 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008423 };
8424
8425 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8426 &CapturedVars, RequiresOuterTask,
8427 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8428 // Fill up the arrays with all the captured variables.
8429 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8430 MappableExprsHandler::MapValuesArrayTy Pointers;
8431 MappableExprsHandler::MapValuesArrayTy Sizes;
8432 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8433
Alexey Bataev8451efa2018-01-15 19:06:12 +00008434 // Get mappable expression information.
8435 MappableExprsHandler MEHandler(D, CGF);
Alexey Bataev969dbc02018-11-08 15:47:39 +00008436 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008437
8438 auto RI = CS.getCapturedRecordDecl()->field_begin();
8439 auto CV = CapturedVars.begin();
8440 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8441 CE = CS.capture_end();
8442 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008443 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8444 MappableExprsHandler::MapValuesArrayTy CurPointers;
8445 MappableExprsHandler::MapValuesArrayTy CurSizes;
8446 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8447 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008448
8449 // VLA sizes are passed to the outlined region by copy and do not have map
8450 // information associated.
8451 if (CI->capturesVariableArrayType()) {
8452 CurBasePointers.push_back(*CV);
8453 CurPointers.push_back(*CV);
8454 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8455 // Copy to the device as an argument. No need to retrieve it.
8456 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8457 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8458 } else {
8459 // If we have any information in the map clause, we use it, otherwise we
8460 // just do a default mapping.
8461 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008462 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008463 if (CurBasePointers.empty())
8464 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8465 CurPointers, CurSizes, CurMapTypes);
Alexey Bataev60705422018-10-30 15:50:12 +00008466 // Generate correct mapping for variables captured by reference in
8467 // lambdas.
8468 if (CI->capturesVariable())
Alexey Bataev969dbc02018-11-08 15:47:39 +00008469 MEHandler.generateInfoForLambdaCaptures(
8470 CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
8471 CurMapTypes, LambdaPointers);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008472 }
8473 // We expect to have at least an element of information for this capture.
8474 assert(!CurBasePointers.empty() &&
8475 "Non-existing map pointer for capture!");
8476 assert(CurBasePointers.size() == CurPointers.size() &&
8477 CurBasePointers.size() == CurSizes.size() &&
8478 CurBasePointers.size() == CurMapTypes.size() &&
8479 "Inconsistent map information sizes!");
8480
Alexey Bataevb3638132018-07-19 16:34:13 +00008481 // If there is an entry in PartialStruct it means we have a struct with
8482 // individual members mapped. Emit an extra combined entry.
8483 if (PartialStruct.Base.isValid())
8484 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8485 CurMapTypes, PartialStruct);
8486
Alexey Bataev8451efa2018-01-15 19:06:12 +00008487 // We need to append the results of this capture to what we already have.
8488 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8489 Pointers.append(CurPointers.begin(), CurPointers.end());
8490 Sizes.append(CurSizes.begin(), CurSizes.end());
8491 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8492 }
Alexey Bataev60705422018-10-30 15:50:12 +00008493 // Adjust MEMBER_OF flags for the lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00008494 MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
8495 Pointers, MapTypes);
Alexey Bataev92327c52018-03-26 16:40:55 +00008496 // Map other list items in the map clause which are not captured variables
8497 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008498 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8499 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008500
8501 TargetDataInfo Info;
8502 // Fill up the arrays and create the arguments.
8503 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8504 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8505 Info.PointersArray, Info.SizesArray,
8506 Info.MapTypesArray, Info);
8507 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8508 InputInfo.BasePointersArray =
8509 Address(Info.BasePointersArray, CGM.getPointerAlign());
8510 InputInfo.PointersArray =
8511 Address(Info.PointersArray, CGM.getPointerAlign());
8512 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8513 MapTypesArray = Info.MapTypesArray;
8514 if (RequiresOuterTask)
8515 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8516 else
8517 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8518 };
8519
8520 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8521 CodeGenFunction &CGF, PrePostActionTy &) {
8522 if (RequiresOuterTask) {
8523 CodeGenFunction::OMPTargetDataInfo InputInfo;
8524 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8525 } else {
8526 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8527 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008528 };
8529
8530 // If we have a target function ID it means that we need to support
8531 // offloading, otherwise, just execute on the host. We need to execute on host
8532 // regardless of the conditional in the if clause if, e.g., the user do not
8533 // specify target triples.
8534 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008535 if (IfCond) {
8536 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8537 } else {
8538 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008539 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008540 }
8541 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008542 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008543 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008544 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008545}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008546
8547void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8548 StringRef ParentName) {
8549 if (!S)
8550 return;
8551
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008552 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008553 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008554 isa<OMPExecutableDirective>(S) &&
8555 isOpenMPTargetExecutionDirective(
8556 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008557
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008558 if (RequiresDeviceCodegen) {
8559 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008560 unsigned DeviceID;
8561 unsigned FileID;
8562 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008563 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008564 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008565
8566 // Is this a target region that should not be emitted as an entry point? If
8567 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008568 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8569 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008570 return;
8571
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008572 switch (E.getDirectiveKind()) {
8573 case OMPD_target:
8574 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8575 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008576 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008577 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008578 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008579 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008580 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008581 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008582 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008583 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008584 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008585 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008586 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008587 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008588 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008589 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008590 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008591 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008592 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008593 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008594 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008595 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008596 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008597 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008598 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008599 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008600 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008601 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008602 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008603 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008604 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008605 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008606 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8607 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008608 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008609 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008610 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008611 CodeGenFunction::
8612 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8613 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008614 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008615 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008616 case OMPD_parallel:
8617 case OMPD_for:
8618 case OMPD_parallel_for:
8619 case OMPD_parallel_sections:
8620 case OMPD_for_simd:
8621 case OMPD_parallel_for_simd:
8622 case OMPD_cancel:
8623 case OMPD_cancellation_point:
8624 case OMPD_ordered:
8625 case OMPD_threadprivate:
8626 case OMPD_task:
8627 case OMPD_simd:
8628 case OMPD_sections:
8629 case OMPD_section:
8630 case OMPD_single:
8631 case OMPD_master:
8632 case OMPD_critical:
8633 case OMPD_taskyield:
8634 case OMPD_barrier:
8635 case OMPD_taskwait:
8636 case OMPD_taskgroup:
8637 case OMPD_atomic:
8638 case OMPD_flush:
8639 case OMPD_teams:
8640 case OMPD_target_data:
8641 case OMPD_target_exit_data:
8642 case OMPD_target_enter_data:
8643 case OMPD_distribute:
8644 case OMPD_distribute_simd:
8645 case OMPD_distribute_parallel_for:
8646 case OMPD_distribute_parallel_for_simd:
8647 case OMPD_teams_distribute:
8648 case OMPD_teams_distribute_simd:
8649 case OMPD_teams_distribute_parallel_for:
8650 case OMPD_teams_distribute_parallel_for_simd:
8651 case OMPD_target_update:
8652 case OMPD_declare_simd:
8653 case OMPD_declare_target:
8654 case OMPD_end_declare_target:
8655 case OMPD_declare_reduction:
8656 case OMPD_taskloop:
8657 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008658 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008659 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008660 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8661 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008662 return;
8663 }
8664
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008665 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008666 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008667 return;
8668
8669 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008670 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008671 return;
8672 }
8673
8674 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008675 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008676 S = L->getBody();
8677
8678 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008679 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008680 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008681}
8682
8683bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008684 // If emitting code for the host, we do not process FD here. Instead we do
8685 // the normal code generation.
8686 if (!CGM.getLangOpts().OpenMPIsDevice)
8687 return false;
8688
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008689 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008690 StringRef Name = CGM.getMangledName(GD);
8691 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008692 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008693 scanForTargetRegionsFunctions(FD->getBody(), Name);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008694
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008695 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008696 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008697 AlreadyEmittedTargetFunctions.count(Name) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008698}
8699
8700bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8701 if (!CGM.getLangOpts().OpenMPIsDevice)
8702 return false;
8703
8704 // Check if there are Ctors/Dtors in this declaration and look for target
8705 // regions in it. We use the complete variant to produce the kernel name
8706 // mangling.
8707 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008708 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8709 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008710 StringRef ParentName =
8711 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8712 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8713 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008714 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008715 StringRef ParentName =
8716 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8717 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8718 }
8719 }
8720
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008721 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008722 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008723 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8724 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008725 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008726 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008727 return true;
8728 }
8729 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008730}
8731
Alexey Bataev03f270c2018-03-30 18:31:07 +00008732void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8733 llvm::Constant *Addr) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008734 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
8735 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
8736 if (!Res) {
8737 if (CGM.getLangOpts().OpenMPIsDevice) {
8738 // Register non-target variables being emitted in device code (debug info
8739 // may cause this).
8740 StringRef VarName = CGM.getMangledName(VD);
8741 EmittedNonTargetVariables.try_emplace(VarName, Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008742 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008743 return;
Alexey Bataev03f270c2018-03-30 18:31:07 +00008744 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008745 // Register declare target variables.
8746 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8747 StringRef VarName;
8748 CharUnits VarSize;
8749 llvm::GlobalValue::LinkageTypes Linkage;
8750 switch (*Res) {
8751 case OMPDeclareTargetDeclAttr::MT_To:
8752 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8753 VarName = CGM.getMangledName(VD);
8754 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8755 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8756 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8757 } else {
8758 VarSize = CharUnits::Zero();
8759 }
8760 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
8761 // Temp solution to prevent optimizations of the internal variables.
8762 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8763 std::string RefName = getName({VarName, "ref"});
8764 if (!CGM.GetGlobalValue(RefName)) {
8765 llvm::Constant *AddrRef =
8766 getOrCreateInternalVariable(Addr->getType(), RefName);
8767 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8768 GVAddrRef->setConstant(/*Val=*/true);
8769 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8770 GVAddrRef->setInitializer(Addr);
8771 CGM.addCompilerUsedGlobal(GVAddrRef);
8772 }
8773 }
8774 break;
8775 case OMPDeclareTargetDeclAttr::MT_Link:
8776 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8777 if (CGM.getLangOpts().OpenMPIsDevice) {
8778 VarName = Addr->getName();
8779 Addr = nullptr;
8780 } else {
8781 VarName = getAddrOfDeclareTargetLink(VD).getName();
8782 Addr = cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8783 }
8784 VarSize = CGM.getPointerSize();
8785 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8786 break;
8787 }
8788 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8789 VarName, Addr, VarSize, Flags, Linkage);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008790}
8791
Samuel Antaoee8fb302016-01-06 13:42:12 +00008792bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008793 if (isa<FunctionDecl>(GD.getDecl()) ||
8794 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008795 return emitTargetFunctions(GD);
8796
8797 return emitTargetGlobalVariable(GD);
8798}
8799
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008800void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8801 for (const VarDecl *VD : DeferredGlobalVariables) {
8802 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008803 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008804 if (!Res)
8805 continue;
8806 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008807 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008808 } else {
8809 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8810 "Expected to or link clauses.");
8811 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008812 }
8813 }
8814}
8815
Alexey Bataev60705422018-10-30 15:50:12 +00008816void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
8817 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
8818 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
8819 " Expected target-based directive.");
8820}
8821
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008822CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8823 CodeGenModule &CGM)
8824 : CGM(CGM) {
8825 if (CGM.getLangOpts().OpenMPIsDevice) {
8826 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8827 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8828 }
8829}
8830
8831CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8832 if (CGM.getLangOpts().OpenMPIsDevice)
8833 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8834}
8835
Alexey Bataev6d944102018-05-02 15:45:28 +00008836bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008837 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8838 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008839
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008840 StringRef Name = CGM.getMangledName(GD);
Alexey Bataev6d944102018-05-02 15:45:28 +00008841 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev34f8a702018-03-28 14:28:54 +00008842 // Do not to emit function if it is marked as declare target as it was already
8843 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008844 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008845 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
8846 if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008847 return !F->isDeclaration();
8848 return false;
8849 }
8850 return true;
8851 }
8852
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008853 return !AlreadyEmittedTargetFunctions.insert(Name).second;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008854}
8855
Samuel Antaoee8fb302016-01-06 13:42:12 +00008856llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8857 // If we have offloading in the current module, we need to emit the entries
8858 // now and register the offloading descriptor.
8859 createOffloadEntriesAndInfoMetadata();
8860
8861 // Create and register the offloading binary descriptors. This is the main
8862 // entity that captures all the information about offloading in the current
8863 // compilation unit.
8864 return createOffloadingBinaryDescriptorRegistration();
8865}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008866
8867void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8868 const OMPExecutableDirective &D,
8869 SourceLocation Loc,
8870 llvm::Value *OutlinedFn,
8871 ArrayRef<llvm::Value *> CapturedVars) {
8872 if (!CGF.HaveInsertPoint())
8873 return;
8874
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008875 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008876 CodeGenFunction::RunCleanupsScope Scope(CGF);
8877
8878 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8879 llvm::Value *Args[] = {
8880 RTLoc,
8881 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8882 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8883 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8884 RealArgs.append(std::begin(Args), std::end(Args));
8885 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8886
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008887 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008888 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8889}
8890
8891void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008892 const Expr *NumTeams,
8893 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008894 SourceLocation Loc) {
8895 if (!CGF.HaveInsertPoint())
8896 return;
8897
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008898 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008899
Carlo Bertollic6872252016-04-04 15:55:02 +00008900 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008901 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008902 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8903 CGF.CGM.Int32Ty, /* isSigned = */ true)
8904 : CGF.Builder.getInt32(0);
8905
8906 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008907 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008908 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8909 CGF.CGM.Int32Ty, /* isSigned = */ true)
8910 : CGF.Builder.getInt32(0);
8911
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008912 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008913 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8914 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008915 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8916 PushNumTeamsArgs);
8917}
Samuel Antaodf158d52016-04-27 22:58:19 +00008918
Samuel Antaocc10b852016-07-28 14:23:26 +00008919void CGOpenMPRuntime::emitTargetDataCalls(
8920 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8921 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008922 if (!CGF.HaveInsertPoint())
8923 return;
8924
Samuel Antaocc10b852016-07-28 14:23:26 +00008925 // Action used to replace the default codegen action and turn privatization
8926 // off.
8927 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008928
8929 // Generate the code for the opening of the data environment. Capture all the
8930 // arguments of the runtime call by reference because they are used in the
8931 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008932 auto &&BeginThenGen = [this, &D, Device, &Info,
8933 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008934 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008935 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008936 MappableExprsHandler::MapValuesArrayTy Pointers;
8937 MappableExprsHandler::MapValuesArrayTy Sizes;
8938 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8939
8940 // Get map clause information.
8941 MappableExprsHandler MCHandler(D, CGF);
8942 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008943
8944 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008945 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008946
8947 llvm::Value *BasePointersArrayArg = nullptr;
8948 llvm::Value *PointersArrayArg = nullptr;
8949 llvm::Value *SizesArrayArg = nullptr;
8950 llvm::Value *MapTypesArrayArg = nullptr;
8951 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008952 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008953
8954 // Emit device ID if any.
8955 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008956 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008957 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008958 CGF.Int64Ty, /*isSigned=*/true);
8959 } else {
8960 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8961 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008962
8963 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008964 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008965
8966 llvm::Value *OffloadingArgs[] = {
8967 DeviceID, PointerNum, BasePointersArrayArg,
8968 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008969 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008970 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008971
8972 // If device pointer privatization is required, emit the body of the region
8973 // here. It will have to be duplicated: with and without privatization.
8974 if (!Info.CaptureDeviceAddrMap.empty())
8975 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008976 };
8977
8978 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008979 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8980 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008981 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008982
8983 llvm::Value *BasePointersArrayArg = nullptr;
8984 llvm::Value *PointersArrayArg = nullptr;
8985 llvm::Value *SizesArrayArg = nullptr;
8986 llvm::Value *MapTypesArrayArg = nullptr;
8987 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008988 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008989
8990 // Emit device ID if any.
8991 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008992 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008993 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008994 CGF.Int64Ty, /*isSigned=*/true);
8995 } else {
8996 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8997 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008998
8999 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009000 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00009001
9002 llvm::Value *OffloadingArgs[] = {
9003 DeviceID, PointerNum, BasePointersArrayArg,
9004 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009005 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00009006 OffloadingArgs);
9007 };
9008
Samuel Antaocc10b852016-07-28 14:23:26 +00009009 // If we need device pointer privatization, we need to emit the body of the
9010 // region with no privatization in the 'else' branch of the conditional.
9011 // Otherwise, we don't have to do anything.
9012 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
9013 PrePostActionTy &) {
9014 if (!Info.CaptureDeviceAddrMap.empty()) {
9015 CodeGen.setAction(NoPrivAction);
9016 CodeGen(CGF);
9017 }
9018 };
9019
9020 // We don't have to do anything to close the region if the if clause evaluates
9021 // to false.
9022 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00009023
9024 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009025 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009026 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009027 RegionCodeGenTy RCG(BeginThenGen);
9028 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009029 }
9030
Samuel Antaocc10b852016-07-28 14:23:26 +00009031 // If we don't require privatization of device pointers, we emit the body in
9032 // between the runtime calls. This avoids duplicating the body code.
9033 if (Info.CaptureDeviceAddrMap.empty()) {
9034 CodeGen.setAction(NoPrivAction);
9035 CodeGen(CGF);
9036 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009037
9038 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009039 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009040 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009041 RegionCodeGenTy RCG(EndThenGen);
9042 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009043 }
9044}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009045
Samuel Antao8d2d7302016-05-26 18:30:22 +00009046void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00009047 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9048 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009049 if (!CGF.HaveInsertPoint())
9050 return;
9051
Samuel Antao8dd66282016-04-27 23:14:30 +00009052 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00009053 isa<OMPTargetExitDataDirective>(D) ||
9054 isa<OMPTargetUpdateDirective>(D)) &&
9055 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00009056
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009057 CodeGenFunction::OMPTargetDataInfo InputInfo;
9058 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009059 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009060 auto &&ThenGen = [this, &D, Device, &InputInfo,
9061 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009062 // Emit device ID if any.
9063 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009064 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009065 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009066 CGF.Int64Ty, /*isSigned=*/true);
9067 } else {
9068 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9069 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009070
9071 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009072 llvm::Constant *PointerNum =
9073 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009074
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009075 llvm::Value *OffloadingArgs[] = {DeviceID,
9076 PointerNum,
9077 InputInfo.BasePointersArray.getPointer(),
9078 InputInfo.PointersArray.getPointer(),
9079 InputInfo.SizesArray.getPointer(),
9080 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00009081
Samuel Antao8d2d7302016-05-26 18:30:22 +00009082 // Select the right runtime function call for each expected standalone
9083 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009084 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00009085 OpenMPRTLFunction RTLFn;
9086 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00009087 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009088 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
9089 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009090 break;
9091 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009092 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
9093 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009094 break;
9095 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009096 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
9097 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009098 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009099 case OMPD_parallel:
9100 case OMPD_for:
9101 case OMPD_parallel_for:
9102 case OMPD_parallel_sections:
9103 case OMPD_for_simd:
9104 case OMPD_parallel_for_simd:
9105 case OMPD_cancel:
9106 case OMPD_cancellation_point:
9107 case OMPD_ordered:
9108 case OMPD_threadprivate:
9109 case OMPD_task:
9110 case OMPD_simd:
9111 case OMPD_sections:
9112 case OMPD_section:
9113 case OMPD_single:
9114 case OMPD_master:
9115 case OMPD_critical:
9116 case OMPD_taskyield:
9117 case OMPD_barrier:
9118 case OMPD_taskwait:
9119 case OMPD_taskgroup:
9120 case OMPD_atomic:
9121 case OMPD_flush:
9122 case OMPD_teams:
9123 case OMPD_target_data:
9124 case OMPD_distribute:
9125 case OMPD_distribute_simd:
9126 case OMPD_distribute_parallel_for:
9127 case OMPD_distribute_parallel_for_simd:
9128 case OMPD_teams_distribute:
9129 case OMPD_teams_distribute_simd:
9130 case OMPD_teams_distribute_parallel_for:
9131 case OMPD_teams_distribute_parallel_for_simd:
9132 case OMPD_declare_simd:
9133 case OMPD_declare_target:
9134 case OMPD_end_declare_target:
9135 case OMPD_declare_reduction:
9136 case OMPD_taskloop:
9137 case OMPD_taskloop_simd:
9138 case OMPD_target:
9139 case OMPD_target_simd:
9140 case OMPD_target_teams_distribute:
9141 case OMPD_target_teams_distribute_simd:
9142 case OMPD_target_teams_distribute_parallel_for:
9143 case OMPD_target_teams_distribute_parallel_for_simd:
9144 case OMPD_target_teams:
9145 case OMPD_target_parallel:
9146 case OMPD_target_parallel_for:
9147 case OMPD_target_parallel_for_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009148 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009149 case OMPD_unknown:
9150 llvm_unreachable("Unexpected standalone target data directive.");
9151 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009152 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009153 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009154 };
9155
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009156 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
9157 CodeGenFunction &CGF, PrePostActionTy &) {
9158 // Fill up the arrays with all the mapped variables.
9159 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
9160 MappableExprsHandler::MapValuesArrayTy Pointers;
9161 MappableExprsHandler::MapValuesArrayTy Sizes;
9162 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009163
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009164 // Get map clause information.
9165 MappableExprsHandler MEHandler(D, CGF);
9166 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
9167
9168 TargetDataInfo Info;
9169 // Fill up the arrays and create the arguments.
9170 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
9171 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
9172 Info.PointersArray, Info.SizesArray,
9173 Info.MapTypesArray, Info);
9174 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
9175 InputInfo.BasePointersArray =
9176 Address(Info.BasePointersArray, CGM.getPointerAlign());
9177 InputInfo.PointersArray =
9178 Address(Info.PointersArray, CGM.getPointerAlign());
9179 InputInfo.SizesArray =
9180 Address(Info.SizesArray, CGM.getPointerAlign());
9181 MapTypesArray = Info.MapTypesArray;
9182 if (D.hasClausesOfKind<OMPDependClause>())
9183 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
9184 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00009185 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009186 };
9187
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009188 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009189 emitOMPIfClause(CGF, IfCond, TargetThenGen,
9190 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009191 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009192 RegionCodeGenTy ThenRCG(TargetThenGen);
9193 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009194 }
9195}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009196
9197namespace {
9198 /// Kind of parameter in a function with 'declare simd' directive.
9199 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
9200 /// Attribute set of the parameter.
9201 struct ParamAttrTy {
9202 ParamKindTy Kind = Vector;
9203 llvm::APSInt StrideOrArg;
9204 llvm::APSInt Alignment;
9205 };
9206} // namespace
9207
9208static unsigned evaluateCDTSize(const FunctionDecl *FD,
9209 ArrayRef<ParamAttrTy> ParamAttrs) {
9210 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
9211 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
9212 // of that clause. The VLEN value must be power of 2.
9213 // In other case the notion of the function`s "characteristic data type" (CDT)
9214 // is used to compute the vector length.
9215 // CDT is defined in the following order:
9216 // a) For non-void function, the CDT is the return type.
9217 // b) If the function has any non-uniform, non-linear parameters, then the
9218 // CDT is the type of the first such parameter.
9219 // c) If the CDT determined by a) or b) above is struct, union, or class
9220 // type which is pass-by-value (except for the type that maps to the
9221 // built-in complex data type), the characteristic data type is int.
9222 // d) If none of the above three cases is applicable, the CDT is int.
9223 // The VLEN is then determined based on the CDT and the size of vector
9224 // register of that ISA for which current vector version is generated. The
9225 // VLEN is computed using the formula below:
9226 // VLEN = sizeof(vector_register) / sizeof(CDT),
9227 // where vector register size specified in section 3.2.1 Registers and the
9228 // Stack Frame of original AMD64 ABI document.
9229 QualType RetType = FD->getReturnType();
9230 if (RetType.isNull())
9231 return 0;
9232 ASTContext &C = FD->getASTContext();
9233 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009234 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009235 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009236 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009237 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009238 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009239 if (ParamAttrs[Offset].Kind == Vector)
9240 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
9241 ++Offset;
9242 }
9243 if (CDT.isNull()) {
9244 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
9245 if (ParamAttrs[I + Offset].Kind == Vector) {
9246 CDT = FD->getParamDecl(I)->getType();
9247 break;
9248 }
9249 }
9250 }
9251 }
9252 if (CDT.isNull())
9253 CDT = C.IntTy;
9254 CDT = CDT->getCanonicalTypeUnqualified();
9255 if (CDT->isRecordType() || CDT->isUnionType())
9256 CDT = C.IntTy;
9257 return C.getTypeSize(CDT);
9258}
9259
9260static void
9261emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00009262 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009263 ArrayRef<ParamAttrTy> ParamAttrs,
9264 OMPDeclareSimdDeclAttr::BranchStateTy State) {
9265 struct ISADataTy {
9266 char ISA;
9267 unsigned VecRegSize;
9268 };
9269 ISADataTy ISAData[] = {
9270 {
9271 'b', 128
9272 }, // SSE
9273 {
9274 'c', 256
9275 }, // AVX
9276 {
9277 'd', 256
9278 }, // AVX2
9279 {
9280 'e', 512
9281 }, // AVX512
9282 };
9283 llvm::SmallVector<char, 2> Masked;
9284 switch (State) {
9285 case OMPDeclareSimdDeclAttr::BS_Undefined:
9286 Masked.push_back('N');
9287 Masked.push_back('M');
9288 break;
9289 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
9290 Masked.push_back('N');
9291 break;
9292 case OMPDeclareSimdDeclAttr::BS_Inbranch:
9293 Masked.push_back('M');
9294 break;
9295 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009296 for (char Mask : Masked) {
9297 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009298 SmallString<256> Buffer;
9299 llvm::raw_svector_ostream Out(Buffer);
9300 Out << "_ZGV" << Data.ISA << Mask;
9301 if (!VLENVal) {
9302 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
9303 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009304 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009305 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009306 }
9307 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009308 switch (ParamAttr.Kind){
9309 case LinearWithVarStride:
9310 Out << 's' << ParamAttr.StrideOrArg;
9311 break;
9312 case Linear:
9313 Out << 'l';
9314 if (!!ParamAttr.StrideOrArg)
9315 Out << ParamAttr.StrideOrArg;
9316 break;
9317 case Uniform:
9318 Out << 'u';
9319 break;
9320 case Vector:
9321 Out << 'v';
9322 break;
9323 }
9324 if (!!ParamAttr.Alignment)
9325 Out << 'a' << ParamAttr.Alignment;
9326 }
9327 Out << '_' << Fn->getName();
9328 Fn->addFnAttr(Out.str());
9329 }
9330 }
9331}
9332
9333void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
9334 llvm::Function *Fn) {
9335 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009336 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009337 // Map params to their positions in function decl.
9338 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
9339 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009340 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009341 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009342 for (const ParmVarDecl *P : FD->parameters()) {
9343 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009344 ++ParamPos;
9345 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009346 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009347 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009348 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
9349 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009350 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009351 E = E->IgnoreParenImpCasts();
9352 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009353 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009354 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009355 } else {
9356 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9357 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009358 Pos = ParamPositions[PVD];
9359 }
9360 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009361 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009362 // Get alignment info.
9363 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009364 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009365 E = E->IgnoreParenImpCasts();
9366 unsigned Pos;
9367 QualType ParmTy;
9368 if (isa<CXXThisExpr>(E)) {
9369 Pos = ParamPositions[FD];
9370 ParmTy = E->getType();
9371 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009372 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9373 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009374 Pos = ParamPositions[PVD];
9375 ParmTy = PVD->getType();
9376 }
9377 ParamAttrs[Pos].Alignment =
9378 (*NI)
9379 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009380 : llvm::APSInt::getUnsigned(
9381 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
9382 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009383 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009384 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009385 // Mark linear parameters.
9386 auto SI = Attr->steps_begin();
9387 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009388 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009389 E = E->IgnoreParenImpCasts();
9390 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009391 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009392 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009393 } else {
9394 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9395 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009396 Pos = ParamPositions[PVD];
9397 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009398 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009399 ParamAttr.Kind = Linear;
9400 if (*SI) {
Fangrui Song407659a2018-11-30 23:41:18 +00009401 Expr::EvalResult Result;
9402 if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009403 if (const auto *DRE =
9404 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9405 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009406 ParamAttr.Kind = LinearWithVarStride;
9407 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9408 ParamPositions[StridePVD->getCanonicalDecl()]);
9409 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009410 }
Fangrui Song407659a2018-11-30 23:41:18 +00009411 } else {
9412 ParamAttr.StrideOrArg = Result.Val.getInt();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009413 }
9414 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009415 ++SI;
9416 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009417 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009418 llvm::APSInt VLENVal;
9419 if (const Expr *VLEN = Attr->getSimdlen())
9420 VLENVal = VLEN->EvaluateKnownConstInt(C);
9421 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9422 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9423 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9424 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009425 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009426 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009427 }
9428}
Alexey Bataev8b427062016-05-25 12:36:08 +00009429
9430namespace {
9431/// Cleanup action for doacross support.
9432class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9433public:
9434 static const int DoacrossFinArgs = 2;
9435
9436private:
9437 llvm::Value *RTLFn;
9438 llvm::Value *Args[DoacrossFinArgs];
9439
9440public:
9441 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
9442 : RTLFn(RTLFn) {
9443 assert(CallArgs.size() == DoacrossFinArgs);
9444 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9445 }
9446 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9447 if (!CGF.HaveInsertPoint())
9448 return;
9449 CGF.EmitRuntimeCall(RTLFn, Args);
9450 }
9451};
9452} // namespace
9453
9454void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009455 const OMPLoopDirective &D,
9456 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009457 if (!CGF.HaveInsertPoint())
9458 return;
9459
9460 ASTContext &C = CGM.getContext();
9461 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9462 RecordDecl *RD;
9463 if (KmpDimTy.isNull()) {
9464 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9465 // kmp_int64 lo; // lower
9466 // kmp_int64 up; // upper
9467 // kmp_int64 st; // stride
9468 // };
9469 RD = C.buildImplicitRecord("kmp_dim");
9470 RD->startDefinition();
9471 addFieldToRecordDecl(C, RD, Int64Ty);
9472 addFieldToRecordDecl(C, RD, Int64Ty);
9473 addFieldToRecordDecl(C, RD, Int64Ty);
9474 RD->completeDefinition();
9475 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009476 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009477 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009478 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009479 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9480 QualType ArrayTy =
9481 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009482
Alexey Bataevf138fda2018-08-13 19:04:24 +00009483 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9484 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009485 enum { LowerFD = 0, UpperFD, StrideFD };
9486 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009487 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
9488 LValue DimsLVal =
9489 CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP(
9490 DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)),
9491 KmpDimTy);
9492 // dims.upper = num_iterations;
9493 LValue UpperLVal = CGF.EmitLValueForField(
9494 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9495 llvm::Value *NumIterVal =
9496 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9497 D.getNumIterations()->getType(), Int64Ty,
9498 D.getNumIterations()->getExprLoc());
9499 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9500 // dims.stride = 1;
9501 LValue StrideLVal = CGF.EmitLValueForField(
9502 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9503 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9504 StrideLVal);
9505 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009506
9507 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9508 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009509 llvm::Value *Args[] = {
9510 emitUpdateLocation(CGF, D.getBeginLoc()),
9511 getThreadID(CGF, D.getBeginLoc()),
9512 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9513 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
9514 CGF.Builder
9515 .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy))
9516 .getPointer(),
9517 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009518
9519 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
9520 CGF.EmitRuntimeCall(RTLFn, Args);
9521 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009522 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
Alexey Bataev8b427062016-05-25 12:36:08 +00009523 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
9524 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9525 llvm::makeArrayRef(FiniArgs));
9526}
9527
9528void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9529 const OMPDependClause *C) {
9530 QualType Int64Ty =
9531 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009532 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9533 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9534 Int64Ty, Size, ArrayType::Normal, 0);
9535 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9536 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9537 const Expr *CounterVal = C->getLoopData(I);
9538 assert(CounterVal);
9539 llvm::Value *CntVal = CGF.EmitScalarConversion(
9540 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9541 CounterVal->getExprLoc());
9542 CGF.EmitStoreOfScalar(
9543 CntVal,
9544 CGF.Builder.CreateConstArrayGEP(
9545 CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)),
9546 /*Volatile=*/false, Int64Ty);
9547 }
9548 llvm::Value *Args[] = {
9549 emitUpdateLocation(CGF, C->getBeginLoc()),
9550 getThreadID(CGF, C->getBeginLoc()),
9551 CGF.Builder
9552 .CreateConstArrayGEP(CntAddr, 0,
9553 CGM.getContext().getTypeSizeInChars(Int64Ty))
9554 .getPointer()};
Alexey Bataev8b427062016-05-25 12:36:08 +00009555 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009556 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009557 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009558 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009559 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9560 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9561 }
9562 CGF.EmitRuntimeCall(RTLFn, Args);
9563}
9564
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009565void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
9566 llvm::Value *Callee,
9567 ArrayRef<llvm::Value *> Args) const {
9568 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009569 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9570
9571 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009572 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009573 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009574 return;
9575 }
9576 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009577 CGF.EmitRuntimeCall(Callee, Args);
9578}
9579
9580void CGOpenMPRuntime::emitOutlinedFunctionCall(
9581 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
9582 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009583 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009584}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009585
9586Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9587 const VarDecl *NativeParam,
9588 const VarDecl *TargetParam) const {
9589 return CGF.GetAddrOfLocalVar(NativeParam);
9590}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009591
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009592Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9593 const VarDecl *VD) {
9594 return Address::invalid();
9595}
9596
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009597llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
9598 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9599 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9600 llvm_unreachable("Not supported in SIMD-only mode");
9601}
9602
9603llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
9604 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9605 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9606 llvm_unreachable("Not supported in SIMD-only mode");
9607}
9608
9609llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
9610 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9611 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9612 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9613 bool Tied, unsigned &NumberOfParts) {
9614 llvm_unreachable("Not supported in SIMD-only mode");
9615}
9616
9617void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9618 SourceLocation Loc,
9619 llvm::Value *OutlinedFn,
9620 ArrayRef<llvm::Value *> CapturedVars,
9621 const Expr *IfCond) {
9622 llvm_unreachable("Not supported in SIMD-only mode");
9623}
9624
9625void CGOpenMPSIMDRuntime::emitCriticalRegion(
9626 CodeGenFunction &CGF, StringRef CriticalName,
9627 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9628 const Expr *Hint) {
9629 llvm_unreachable("Not supported in SIMD-only mode");
9630}
9631
9632void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9633 const RegionCodeGenTy &MasterOpGen,
9634 SourceLocation Loc) {
9635 llvm_unreachable("Not supported in SIMD-only mode");
9636}
9637
9638void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9639 SourceLocation Loc) {
9640 llvm_unreachable("Not supported in SIMD-only mode");
9641}
9642
9643void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9644 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9645 SourceLocation Loc) {
9646 llvm_unreachable("Not supported in SIMD-only mode");
9647}
9648
9649void CGOpenMPSIMDRuntime::emitSingleRegion(
9650 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9651 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9652 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9653 ArrayRef<const Expr *> AssignmentOps) {
9654 llvm_unreachable("Not supported in SIMD-only mode");
9655}
9656
9657void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9658 const RegionCodeGenTy &OrderedOpGen,
9659 SourceLocation Loc,
9660 bool IsThreads) {
9661 llvm_unreachable("Not supported in SIMD-only mode");
9662}
9663
9664void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9665 SourceLocation Loc,
9666 OpenMPDirectiveKind Kind,
9667 bool EmitChecks,
9668 bool ForceSimpleCall) {
9669 llvm_unreachable("Not supported in SIMD-only mode");
9670}
9671
9672void CGOpenMPSIMDRuntime::emitForDispatchInit(
9673 CodeGenFunction &CGF, SourceLocation Loc,
9674 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9675 bool Ordered, const DispatchRTInput &DispatchValues) {
9676 llvm_unreachable("Not supported in SIMD-only mode");
9677}
9678
9679void CGOpenMPSIMDRuntime::emitForStaticInit(
9680 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9681 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9682 llvm_unreachable("Not supported in SIMD-only mode");
9683}
9684
9685void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9686 CodeGenFunction &CGF, SourceLocation Loc,
9687 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9688 llvm_unreachable("Not supported in SIMD-only mode");
9689}
9690
9691void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9692 SourceLocation Loc,
9693 unsigned IVSize,
9694 bool IVSigned) {
9695 llvm_unreachable("Not supported in SIMD-only mode");
9696}
9697
9698void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9699 SourceLocation Loc,
9700 OpenMPDirectiveKind DKind) {
9701 llvm_unreachable("Not supported in SIMD-only mode");
9702}
9703
9704llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9705 SourceLocation Loc,
9706 unsigned IVSize, bool IVSigned,
9707 Address IL, Address LB,
9708 Address UB, Address ST) {
9709 llvm_unreachable("Not supported in SIMD-only mode");
9710}
9711
9712void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9713 llvm::Value *NumThreads,
9714 SourceLocation Loc) {
9715 llvm_unreachable("Not supported in SIMD-only mode");
9716}
9717
9718void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9719 OpenMPProcBindClauseKind ProcBind,
9720 SourceLocation Loc) {
9721 llvm_unreachable("Not supported in SIMD-only mode");
9722}
9723
9724Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9725 const VarDecl *VD,
9726 Address VDAddr,
9727 SourceLocation Loc) {
9728 llvm_unreachable("Not supported in SIMD-only mode");
9729}
9730
9731llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9732 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9733 CodeGenFunction *CGF) {
9734 llvm_unreachable("Not supported in SIMD-only mode");
9735}
9736
9737Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9738 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9739 llvm_unreachable("Not supported in SIMD-only mode");
9740}
9741
9742void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9743 ArrayRef<const Expr *> Vars,
9744 SourceLocation Loc) {
9745 llvm_unreachable("Not supported in SIMD-only mode");
9746}
9747
9748void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9749 const OMPExecutableDirective &D,
9750 llvm::Value *TaskFunction,
9751 QualType SharedsTy, Address Shareds,
9752 const Expr *IfCond,
9753 const OMPTaskDataTy &Data) {
9754 llvm_unreachable("Not supported in SIMD-only mode");
9755}
9756
9757void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9758 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
9759 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
9760 const Expr *IfCond, const OMPTaskDataTy &Data) {
9761 llvm_unreachable("Not supported in SIMD-only mode");
9762}
9763
9764void CGOpenMPSIMDRuntime::emitReduction(
9765 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9766 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9767 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9768 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9769 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9770 ReductionOps, Options);
9771}
9772
9773llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9774 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9775 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9776 llvm_unreachable("Not supported in SIMD-only mode");
9777}
9778
9779void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9780 SourceLocation Loc,
9781 ReductionCodeGen &RCG,
9782 unsigned N) {
9783 llvm_unreachable("Not supported in SIMD-only mode");
9784}
9785
9786Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9787 SourceLocation Loc,
9788 llvm::Value *ReductionsPtr,
9789 LValue SharedLVal) {
9790 llvm_unreachable("Not supported in SIMD-only mode");
9791}
9792
9793void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9794 SourceLocation Loc) {
9795 llvm_unreachable("Not supported in SIMD-only mode");
9796}
9797
9798void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9799 CodeGenFunction &CGF, SourceLocation Loc,
9800 OpenMPDirectiveKind CancelRegion) {
9801 llvm_unreachable("Not supported in SIMD-only mode");
9802}
9803
9804void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9805 SourceLocation Loc, const Expr *IfCond,
9806 OpenMPDirectiveKind CancelRegion) {
9807 llvm_unreachable("Not supported in SIMD-only mode");
9808}
9809
9810void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9811 const OMPExecutableDirective &D, StringRef ParentName,
9812 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9813 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9814 llvm_unreachable("Not supported in SIMD-only mode");
9815}
9816
9817void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9818 const OMPExecutableDirective &D,
9819 llvm::Value *OutlinedFn,
9820 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00009821 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009822 llvm_unreachable("Not supported in SIMD-only mode");
9823}
9824
9825bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9826 llvm_unreachable("Not supported in SIMD-only mode");
9827}
9828
9829bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9830 llvm_unreachable("Not supported in SIMD-only mode");
9831}
9832
9833bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9834 return false;
9835}
9836
9837llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9838 return nullptr;
9839}
9840
9841void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9842 const OMPExecutableDirective &D,
9843 SourceLocation Loc,
9844 llvm::Value *OutlinedFn,
9845 ArrayRef<llvm::Value *> CapturedVars) {
9846 llvm_unreachable("Not supported in SIMD-only mode");
9847}
9848
9849void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9850 const Expr *NumTeams,
9851 const Expr *ThreadLimit,
9852 SourceLocation Loc) {
9853 llvm_unreachable("Not supported in SIMD-only mode");
9854}
9855
9856void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9857 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9858 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9859 llvm_unreachable("Not supported in SIMD-only mode");
9860}
9861
9862void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9863 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9864 const Expr *Device) {
9865 llvm_unreachable("Not supported in SIMD-only mode");
9866}
9867
9868void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009869 const OMPLoopDirective &D,
9870 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009871 llvm_unreachable("Not supported in SIMD-only mode");
9872}
9873
9874void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9875 const OMPDependClause *C) {
9876 llvm_unreachable("Not supported in SIMD-only mode");
9877}
9878
9879const VarDecl *
9880CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9881 const VarDecl *NativeParam) const {
9882 llvm_unreachable("Not supported in SIMD-only mode");
9883}
9884
9885Address
9886CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9887 const VarDecl *NativeParam,
9888 const VarDecl *TargetParam) const {
9889 llvm_unreachable("Not supported in SIMD-only mode");
9890}
9891