blob: 4ed63e0084c1ae12ba1af57d45a6d21ee3506107 [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 Bataev9959db52014-05-06 10:08:46 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/GlobalValue.h"
26#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000027#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000029#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000030
31using namespace clang;
32using namespace CodeGen;
33
Benjamin Kramerc52193f2014-10-10 13:57:57 +000034namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000035/// Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000036class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
37public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000038 /// Kinds of OpenMP regions used in codegen.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000039 enum CGOpenMPRegionKind {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000040 /// Region with outlined function for standalone 'parallel'
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000041 /// directive.
42 ParallelOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000043 /// Region with outlined function for standalone 'task' directive.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000044 TaskOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Region for constructs that do not require function outlining,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 /// like 'for', 'sections', 'atomic' etc. directives.
47 InlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000048 /// Region with outlined function for standalone 'target' directive.
Samuel Antaobed3c462015-10-02 16:14:20 +000049 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000050 };
Alexey Bataev18095712014-10-10 12:19:54 +000051
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 CGOpenMPRegionInfo(const CapturedStmt &CS,
53 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000054 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
55 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000056 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000057 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058
59 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000060 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
61 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000062 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000063 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000064
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000065 /// Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000066 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000067 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000068
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000069 /// Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000070 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000071
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000072 /// Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000073 /// \return LValue for thread id variable. This LValue always has type int32*.
74 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000075
Alexey Bataev48591dd2016-04-20 04:01:36 +000076 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
77
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000078 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000079
Alexey Bataev81c7ea02015-07-03 09:56:58 +000080 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
81
Alexey Bataev25e5b442015-09-15 12:52:43 +000082 bool hasCancel() const { return HasCancel; }
83
Alexey Bataev18095712014-10-10 12:19:54 +000084 static bool classof(const CGCapturedStmtInfo *Info) {
85 return Info->getKind() == CR_OpenMP;
86 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000087
Alexey Bataev48591dd2016-04-20 04:01:36 +000088 ~CGOpenMPRegionInfo() override = default;
89
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000091 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000092 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000093 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000094 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000095};
Alexey Bataev18095712014-10-10 12:19:54 +000096
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000097/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000098class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000099public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000101 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000102 OpenMPDirectiveKind Kind, bool HasCancel,
103 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000104 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
105 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000107 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
108 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000109
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000110 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000111 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000112 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000113
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000114 /// Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000115 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000116
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000117 static bool classof(const CGCapturedStmtInfo *Info) {
118 return CGOpenMPRegionInfo::classof(Info) &&
119 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
120 ParallelOutlinedRegion;
121 }
122
Alexey Bataev18095712014-10-10 12:19:54 +0000123private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000124 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev18095712014-10-10 12:19:54 +0000125 /// constructs.
126 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000127 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000128};
129
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000130/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000131class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133 class UntiedTaskActionTy final : public PrePostActionTy {
134 bool Untied;
135 const VarDecl *PartIDVar;
136 const RegionCodeGenTy UntiedCodeGen;
137 llvm::SwitchInst *UntiedSwitch = nullptr;
138
139 public:
140 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
141 const RegionCodeGenTy &UntiedCodeGen)
142 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
143 void Enter(CodeGenFunction &CGF) override {
144 if (Untied) {
145 // Emit task switching point.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000146 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000147 CGF.GetAddrOfLocalVar(PartIDVar),
148 PartIDVar->getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000149 llvm::Value *Res =
150 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
151 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
Alexey Bataev48591dd2016-04-20 04:01:36 +0000152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153 CGF.EmitBlock(DoneBB);
154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157 CGF.Builder.GetInsertBlock());
158 emitUntiedSwitch(CGF);
159 }
160 }
161 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 if (Untied) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000163 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167 PartIdLVal);
168 UntiedCodeGen(CGF);
169 CodeGenFunction::JumpDest CurPoint =
170 CGF.getJumpDestInCurrentScope(".untied.next.");
171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174 CGF.Builder.GetInsertBlock());
175 CGF.EmitBranchThroughCleanup(CurPoint);
176 CGF.EmitBlock(CurPoint.getBlock());
177 }
178 }
179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000182 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000183 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 OpenMPDirectiveKind Kind, bool HasCancel,
185 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000187 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
189 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000191 /// Get a variable or parameter for storing global thread id
Alexey Bataev62b63b12015-03-10 07:28:44 +0000192 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000195 /// Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000198 /// Get the name of the capture helper.
Alexey Bataev62b63b12015-03-10 07:28:44 +0000199 StringRef getHelperName() const override { return ".omp_outlined."; }
200
Alexey Bataev48591dd2016-04-20 04:01:36 +0000201 void emitUntiedSwitch(CodeGenFunction &CGF) override {
202 Action.emitUntiedSwitch(CGF);
203 }
204
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000205 static bool classof(const CGCapturedStmtInfo *Info) {
206 return CGOpenMPRegionInfo::classof(Info) &&
207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208 TaskOutlinedRegion;
209 }
210
Alexey Bataev62b63b12015-03-10 07:28:44 +0000211private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000212 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev62b63b12015-03-10 07:28:44 +0000213 /// constructs.
214 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000215 /// Action for emitting code for untied tasks.
216 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000217};
218
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000219/// API for inlined captured statement code generation in OpenMP
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000220/// constructs.
221class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000224 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000225 OpenMPDirectiveKind Kind, bool HasCancel)
226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000230 // Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000231 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 if (OuterRegionInfo)
233 return OuterRegionInfo->getContextValue();
234 llvm_unreachable("No context value for inlined OpenMP region");
235 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000236
Hans Wennborg7eb54642015-09-10 17:07:54 +0000237 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238 if (OuterRegionInfo) {
239 OuterRegionInfo->setContextValue(V);
240 return;
241 }
242 llvm_unreachable("No context value for inlined OpenMP region");
243 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000245 /// Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 if (OuterRegionInfo)
248 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000249 // If there is no outer outlined region,no need to lookup in a list of
250 // captured variables, we can use the original one.
251 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000253
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000254 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000255 if (OuterRegionInfo)
256 return OuterRegionInfo->getThisFieldDecl();
257 return nullptr;
258 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000259
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000260 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000261 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000262 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 if (OuterRegionInfo)
264 return OuterRegionInfo->getThreadIDVariable();
265 return nullptr;
266 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000268 /// Get an LValue for the current ThreadID variable.
Alexey Bataev311a9282017-10-12 13:51:32 +0000269 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
270 if (OuterRegionInfo)
271 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
272 llvm_unreachable("No LValue for inlined OpenMP construct");
273 }
274
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000275 /// Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000276 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000277 if (auto *OuterRegionInfo = getOldCSI())
278 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 llvm_unreachable("No helper name for inlined OpenMP construct");
280 }
281
Alexey Bataev48591dd2016-04-20 04:01:36 +0000282 void emitUntiedSwitch(CodeGenFunction &CGF) override {
283 if (OuterRegionInfo)
284 OuterRegionInfo->emitUntiedSwitch(CGF);
285 }
286
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000287 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
288
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000289 static bool classof(const CGCapturedStmtInfo *Info) {
290 return CGOpenMPRegionInfo::classof(Info) &&
291 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
292 }
293
Alexey Bataev48591dd2016-04-20 04:01:36 +0000294 ~CGOpenMPInlinedRegionInfo() override = default;
295
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000296private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000297 /// CodeGen info about outer OpenMP region.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000298 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
299 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000300};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000301
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000302/// API for captured statement code generation in OpenMP target
Samuel Antaobed3c462015-10-02 16:14:20 +0000303/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304/// captured fields. The name of the target region has to be unique in a given
305/// application so it is provided by the client, because only the client has
306/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000307class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000308public:
309 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000310 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000311 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 /*HasCancel=*/false),
313 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000314
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000315 /// This is unused for target regions because each starts executing
Samuel Antaobed3c462015-10-02 16:14:20 +0000316 /// with a single thread.
317 const VarDecl *getThreadIDVariable() const override { return nullptr; }
318
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000319 /// Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000320 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000321
322 static bool classof(const CGCapturedStmtInfo *Info) {
323 return CGOpenMPRegionInfo::classof(Info) &&
324 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
325 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000326
327private:
328 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000329};
330
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000331static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000332 llvm_unreachable("No codegen for expressions");
333}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000334/// API for generation of expressions captured in a innermost OpenMP
Samuel Antaob68e2db2016-03-03 16:20:23 +0000335/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000336class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337public:
338 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
339 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
340 OMPD_unknown,
341 /*HasCancel=*/false),
342 PrivScope(CGF) {
343 // Make sure the globals captured in the provided statement are local by
344 // using the privatization logic. We assume the same variable is not
345 // captured more than once.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000346 for (const auto &C : CS.captures()) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000347 if (!C.capturesVariable() && !C.capturesVariableByCopy())
348 continue;
349
350 const VarDecl *VD = C.getCapturedVar();
351 if (VD->isLocalVarDeclOrParm())
352 continue;
353
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000354 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Samuel Antaob68e2db2016-03-03 16:20:23 +0000355 /*RefersToEnclosingVariableOrCapture=*/false,
356 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000357 C.getLocation());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000358 PrivScope.addPrivate(
359 VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
Samuel Antaob68e2db2016-03-03 16:20:23 +0000360 }
361 (void)PrivScope.Privatize();
362 }
363
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000364 /// Lookup the captured field decl for a variable.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000365 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000366 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
Samuel Antaob68e2db2016-03-03 16:20:23 +0000367 return FD;
368 return nullptr;
369 }
370
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000371 /// Emit the captured statement body.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000372 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
373 llvm_unreachable("No body for expressions");
374 }
375
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000376 /// Get a variable or parameter for storing global thread id
Samuel Antaob68e2db2016-03-03 16:20:23 +0000377 /// inside OpenMP construct.
378 const VarDecl *getThreadIDVariable() const override {
379 llvm_unreachable("No thread id for expressions");
380 }
381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000382 /// Get the name of the capture helper.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000383 StringRef getHelperName() const override {
384 llvm_unreachable("No helper name for expressions");
385 }
386
387 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
388
389private:
390 /// Private scope to capture global variables.
391 CodeGenFunction::OMPPrivateScope PrivScope;
392};
393
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000394/// RAII for emitting code of OpenMP constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000395class InlinedOpenMPRegionRAII {
396 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000397 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
398 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000399 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000400
401public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000402 /// Constructs region for combined constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000403 /// \param CodeGen Code generation sequence for combined directives. Includes
404 /// a list of functions used for code generation of implicitly inlined
405 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000406 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000407 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000408 : CGF(CGF) {
409 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000410 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
411 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000412 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
413 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
414 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000415 BlockInfo = CGF.BlockInfo;
416 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000417 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000418
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000419 ~InlinedOpenMPRegionRAII() {
420 // Restore original CapturedStmtInfo only if we're done with code emission.
421 auto *OldCSI =
422 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
423 delete CGF.CapturedStmtInfo;
424 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000425 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
426 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000427 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000428 }
429};
430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000431/// Values for bit flags used in the ident_t to describe the fields.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000432/// All enumeric elements are named and described in accordance with the code
James Y Knight5d71fc52019-01-29 16:37:27 +0000433/// from https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000434enum OpenMPLocationFlags : unsigned {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000435 /// Use trampoline for internal microtask.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000436 OMP_IDENT_IMD = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Use c-style ident structure.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000438 OMP_IDENT_KMPC = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000439 /// Atomic reduction option for kmpc_reduce.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000440 OMP_ATOMIC_REDUCE = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000441 /// Explicit 'barrier' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000442 OMP_IDENT_BARRIER_EXPL = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000443 /// Implicit barrier in code.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000444 OMP_IDENT_BARRIER_IMPL = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445 /// Implicit barrier in 'for' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000446 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// Implicit barrier in 'sections' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000448 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000449 /// Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000450 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
451 /// Call of __kmp_for_static_init for static loop.
452 OMP_IDENT_WORK_LOOP = 0x200,
453 /// Call of __kmp_for_static_init for sections.
454 OMP_IDENT_WORK_SECTIONS = 0x400,
455 /// Call of __kmp_for_static_init for distribute.
456 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
457 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000458};
459
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000460/// Describes ident structure that describes a source location.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000461/// All descriptions are taken from
James Y Knight5d71fc52019-01-29 16:37:27 +0000462/// https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h
Alexey Bataev50b3c952016-02-19 10:38:26 +0000463/// Original structure:
464/// typedef struct ident {
465/// kmp_int32 reserved_1; /**< might be used in Fortran;
466/// see above */
467/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
468/// KMP_IDENT_KMPC identifies this union
469/// member */
470/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
471/// see above */
472///#if USE_ITT_BUILD
473/// /* but currently used for storing
474/// region-specific ITT */
475/// /* contextual information. */
476///#endif /* USE_ITT_BUILD */
477/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
478/// C++ */
479/// char const *psource; /**< String describing the source location.
480/// The string is composed of semi-colon separated
481// fields which describe the source file,
482/// the function and a pair of line numbers that
483/// delimit the construct.
484/// */
485/// } ident_t;
486enum IdentFieldIndex {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000487 /// might be used in Fortran
Alexey Bataev50b3c952016-02-19 10:38:26 +0000488 IdentField_Reserved_1,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000489 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000490 IdentField_Flags,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000491 /// Not really used in Fortran any more
Alexey Bataev50b3c952016-02-19 10:38:26 +0000492 IdentField_Reserved_2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Source[4] in Fortran, do not use for C++
Alexey Bataev50b3c952016-02-19 10:38:26 +0000494 IdentField_Reserved_3,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// String describing the source location. The string is composed of
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 /// semi-colon separated fields which describe the source file, the function
497 /// and a pair of line numbers that delimit the construct.
498 IdentField_PSource
499};
500
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000501/// Schedule types for 'omp for' loops (these enumerators are taken from
Alexey Bataev50b3c952016-02-19 10:38:26 +0000502/// the enum sched_type in kmp.h).
503enum OpenMPSchedType {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000504 /// Lower bound for default (unordered) versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000505 OMP_sch_lower = 32,
506 OMP_sch_static_chunked = 33,
507 OMP_sch_static = 34,
508 OMP_sch_dynamic_chunked = 35,
509 OMP_sch_guided_chunked = 36,
510 OMP_sch_runtime = 37,
511 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000512 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000513 OMP_sch_static_balanced_chunked = 45,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000514 /// Lower bound for 'ordered' versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000515 OMP_ord_lower = 64,
516 OMP_ord_static_chunked = 65,
517 OMP_ord_static = 66,
518 OMP_ord_dynamic_chunked = 67,
519 OMP_ord_guided_chunked = 68,
520 OMP_ord_runtime = 69,
521 OMP_ord_auto = 70,
522 OMP_sch_default = OMP_sch_static,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000523 /// dist_schedule types
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000524 OMP_dist_sch_static_chunked = 91,
525 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000526 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
527 /// Set if the monotonic schedule modifier was present.
528 OMP_sch_modifier_monotonic = (1 << 29),
529 /// Set if the nonmonotonic schedule modifier was present.
530 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000531};
532
533enum OpenMPRTLFunction {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000534 /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000535 /// kmpc_micro microtask, ...);
536 OMPRTL__kmpc_fork_call,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000537 /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000538 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
539 OMPRTL__kmpc_threadprivate_cached,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000540 /// Call to void __kmpc_threadprivate_register( ident_t *,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000541 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
542 OMPRTL__kmpc_threadprivate_register,
543 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
544 OMPRTL__kmpc_global_thread_num,
545 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
546 // kmp_critical_name *crit);
547 OMPRTL__kmpc_critical,
548 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
549 // global_tid, kmp_critical_name *crit, uintptr_t hint);
550 OMPRTL__kmpc_critical_with_hint,
551 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
552 // kmp_critical_name *crit);
553 OMPRTL__kmpc_end_critical,
554 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
555 // global_tid);
556 OMPRTL__kmpc_cancel_barrier,
557 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
558 OMPRTL__kmpc_barrier,
559 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
560 OMPRTL__kmpc_for_static_fini,
561 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
562 // global_tid);
563 OMPRTL__kmpc_serialized_parallel,
564 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
565 // global_tid);
566 OMPRTL__kmpc_end_serialized_parallel,
567 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
568 // kmp_int32 num_threads);
569 OMPRTL__kmpc_push_num_threads,
570 // Call to void __kmpc_flush(ident_t *loc);
571 OMPRTL__kmpc_flush,
572 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
573 OMPRTL__kmpc_master,
574 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
575 OMPRTL__kmpc_end_master,
576 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
577 // int end_part);
578 OMPRTL__kmpc_omp_taskyield,
579 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
580 OMPRTL__kmpc_single,
581 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
582 OMPRTL__kmpc_end_single,
583 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
584 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
585 // kmp_routine_entry_t *task_entry);
586 OMPRTL__kmpc_omp_task_alloc,
587 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
588 // new_task);
589 OMPRTL__kmpc_omp_task,
590 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
591 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
592 // kmp_int32 didit);
593 OMPRTL__kmpc_copyprivate,
594 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
595 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
596 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
597 OMPRTL__kmpc_reduce,
598 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
599 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
600 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
601 // *lck);
602 OMPRTL__kmpc_reduce_nowait,
603 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
604 // kmp_critical_name *lck);
605 OMPRTL__kmpc_end_reduce,
606 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
607 // kmp_critical_name *lck);
608 OMPRTL__kmpc_end_reduce_nowait,
609 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
610 // kmp_task_t * new_task);
611 OMPRTL__kmpc_omp_task_begin_if0,
612 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
613 // kmp_task_t * new_task);
614 OMPRTL__kmpc_omp_task_complete_if0,
615 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
616 OMPRTL__kmpc_ordered,
617 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
618 OMPRTL__kmpc_end_ordered,
619 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
620 // global_tid);
621 OMPRTL__kmpc_omp_taskwait,
622 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
623 OMPRTL__kmpc_taskgroup,
624 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
625 OMPRTL__kmpc_end_taskgroup,
626 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
627 // int proc_bind);
628 OMPRTL__kmpc_push_proc_bind,
629 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
630 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
631 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
632 OMPRTL__kmpc_omp_task_with_deps,
633 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
634 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
635 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
636 OMPRTL__kmpc_omp_wait_deps,
637 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
638 // global_tid, kmp_int32 cncl_kind);
639 OMPRTL__kmpc_cancellationpoint,
640 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
641 // kmp_int32 cncl_kind);
642 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000643 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
644 // kmp_int32 num_teams, kmp_int32 thread_limit);
645 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000646 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
647 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000648 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000649 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
650 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
651 // sched, kmp_uint64 grainsize, void *task_dup);
652 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000653 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
654 // num_dims, struct kmp_dim *dims);
655 OMPRTL__kmpc_doacross_init,
656 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
657 OMPRTL__kmpc_doacross_fini,
658 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
659 // *vec);
660 OMPRTL__kmpc_doacross_post,
661 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
662 // *vec);
663 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000664 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
665 // *data);
666 OMPRTL__kmpc_task_reduction_init,
667 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
668 // *d);
669 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000670
671 //
672 // Offloading related calls
673 //
Alexey Bataev7bb33532019-01-07 21:30:43 +0000674 // Call to void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
675 // size);
676 OMPRTL__kmpc_push_target_tripcount,
George Rokos63bc9d62017-11-21 18:25:12 +0000677 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
678 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000679 // *arg_types);
680 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000681 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
682 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
683 // *arg_types);
684 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000685 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
686 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
687 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000688 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000689 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
690 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
691 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
692 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000693 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
694 OMPRTL__tgt_register_lib,
695 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
696 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000697 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
698 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000699 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000700 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
701 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
702 // *arg_types);
703 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000704 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
705 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000706 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000707 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
708 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
709 // *arg_types);
710 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000711 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
712 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000713 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000714 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
715 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
716 // *arg_types);
717 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000718};
719
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000720/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
721/// region.
722class CleanupTy final : public EHScopeStack::Cleanup {
723 PrePostActionTy *Action;
724
725public:
726 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
727 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
728 if (!CGF.HaveInsertPoint())
729 return;
730 Action->Exit(CGF);
731 }
732};
733
Hans Wennborg7eb54642015-09-10 17:07:54 +0000734} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000735
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000736void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
737 CodeGenFunction::RunCleanupsScope Scope(CGF);
738 if (PrePostAction) {
739 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
740 Callback(CodeGen, CGF, *PrePostAction);
741 } else {
742 PrePostActionTy Action;
743 Callback(CodeGen, CGF, Action);
744 }
745}
746
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000747/// Check if the combiner is a call to UDR combiner and if it is so return the
748/// UDR decl used for reduction.
749static const OMPDeclareReductionDecl *
750getReductionInit(const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000751 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
752 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
753 if (const auto *DRE =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000754 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000755 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000756 return DRD;
757 return nullptr;
758}
759
760static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
761 const OMPDeclareReductionDecl *DRD,
762 const Expr *InitOp,
763 Address Private, Address Original,
764 QualType Ty) {
765 if (DRD->getInitializer()) {
766 std::pair<llvm::Function *, llvm::Function *> Reduction =
767 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000768 const auto *CE = cast<CallExpr>(InitOp);
769 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000770 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
771 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000772 const auto *LHSDRE =
773 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
774 const auto *RHSDRE =
775 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000776 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
777 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000778 [=]() { return Private; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000779 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000780 [=]() { return Original; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000781 (void)PrivateScope.Privatize();
782 RValue Func = RValue::get(Reduction.second);
783 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
784 CGF.EmitIgnoredExpr(InitOp);
785 } else {
786 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
Alexey Bataev18fa2322018-05-02 14:20:50 +0000787 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000788 auto *GV = new llvm::GlobalVariable(
789 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
Alexey Bataev18fa2322018-05-02 14:20:50 +0000790 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000791 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
792 RValue InitRVal;
793 switch (CGF.getEvaluationKind(Ty)) {
794 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000795 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000796 break;
797 case TEK_Complex:
798 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000799 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000800 break;
801 case TEK_Aggregate:
802 InitRVal = RValue::getAggregate(LV.getAddress());
803 break;
804 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000805 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000806 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
807 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
808 /*IsInitializer=*/false);
809 }
810}
811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000812/// Emit initialization of arrays of complex types.
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000813/// \param DestAddr Address of the array.
814/// \param Type Type of array.
815/// \param Init Initial expression of array.
816/// \param SrcAddr Address of the original array.
817static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000818 QualType Type, bool EmitDeclareReductionInit,
819 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000820 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000821 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000822 // Perform element-by-element initialization.
823 QualType ElementTy;
824
825 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000826 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
827 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000828 DestAddr =
829 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
830 if (DRD)
831 SrcAddr =
832 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
833
834 llvm::Value *SrcBegin = nullptr;
835 if (DRD)
836 SrcBegin = SrcAddr.getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000837 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000838 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000839 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000840 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000841 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
842 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
843 llvm::Value *IsEmpty =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000844 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
845 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
846
847 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000848 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000849 CGF.EmitBlock(BodyBB);
850
851 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
852
853 llvm::PHINode *SrcElementPHI = nullptr;
854 Address SrcElementCurrent = Address::invalid();
855 if (DRD) {
856 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
857 "omp.arraycpy.srcElementPast");
858 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
859 SrcElementCurrent =
860 Address(SrcElementPHI,
861 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
862 }
863 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
864 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
865 DestElementPHI->addIncoming(DestBegin, EntryBB);
866 Address DestElementCurrent =
867 Address(DestElementPHI,
868 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
869
870 // Emit copy.
871 {
872 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000873 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000874 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
875 SrcElementCurrent, ElementTy);
876 } else
877 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
878 /*IsInitializer=*/false);
879 }
880
881 if (DRD) {
882 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000883 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000884 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
885 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
886 }
887
888 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000889 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000890 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
891 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000892 llvm::Value *Done =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000893 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
894 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
895 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
896
897 // Done.
898 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
899}
900
901LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000902 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000903}
904
905LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
906 const Expr *E) {
907 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
908 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
909 return LValue();
910}
911
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000912void ReductionCodeGen::emitAggregateInitialization(
913 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
914 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000915 // Emit VarDecl with copy init for arrays.
916 // Get the address of the original variable captured in current
917 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000918 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000919 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000920 bool EmitDeclareReductionInit =
921 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000922 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000923 EmitDeclareReductionInit,
924 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
925 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000926 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000927}
928
929ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
930 ArrayRef<const Expr *> Privates,
931 ArrayRef<const Expr *> ReductionOps) {
932 ClausesData.reserve(Shareds.size());
933 SharedAddresses.reserve(Shareds.size());
934 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000935 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000936 auto IPriv = Privates.begin();
937 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000938 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000939 ClausesData.emplace_back(Ref, *IPriv, *IRed);
940 std::advance(IPriv, 1);
941 std::advance(IRed, 1);
942 }
943}
944
945void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
946 assert(SharedAddresses.size() == N &&
947 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000948 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
949 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
950 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000951}
952
953void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000954 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000955 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
956 QualType PrivateType = PrivateVD->getType();
957 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000958 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000959 Sizes.emplace_back(
960 CGF.getTypeSize(
961 SharedAddresses[N].first.getType().getNonReferenceType()),
962 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000963 return;
964 }
965 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000966 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000967 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000968 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
969 ->getElementType();
970 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000971 if (AsArraySection) {
972 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
973 SharedAddresses[N].first.getPointer());
974 Size = CGF.Builder.CreateNUWAdd(
975 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000976 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000977 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000978 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000979 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000980 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000981 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000982 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000983 CodeGenFunction::OpaqueValueMapping OpaqueMap(
984 CGF,
985 cast<OpaqueValueExpr>(
986 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
987 RValue::get(Size));
988 CGF.EmitVariablyModifiedType(PrivateType);
989}
990
991void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
992 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000993 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000994 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
995 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000996 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000997 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000998 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000999 "items.");
1000 return;
1001 }
1002 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1003 CGF,
1004 cast<OpaqueValueExpr>(
1005 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1006 RValue::get(Size));
1007 CGF.EmitVariablyModifiedType(PrivateType);
1008}
1009
1010void ReductionCodeGen::emitInitialization(
1011 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1012 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1013 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001014 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001015 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001016 const OMPDeclareReductionDecl *DRD =
1017 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001018 QualType PrivateType = PrivateVD->getType();
1019 PrivateAddr = CGF.Builder.CreateElementBitCast(
1020 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1021 QualType SharedType = SharedAddresses[N].first.getType();
1022 SharedLVal = CGF.MakeAddrLValue(
1023 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1024 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001025 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001026 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001027 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001028 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001029 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1030 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1031 PrivateAddr, SharedLVal.getAddress(),
1032 SharedLVal.getType());
1033 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1034 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1035 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1036 PrivateVD->getType().getQualifiers(),
1037 /*IsInitializer=*/false);
1038 }
1039}
1040
1041bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001042 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001043 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1044 QualType PrivateType = PrivateVD->getType();
1045 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1046 return DTorKind != QualType::DK_none;
1047}
1048
1049void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1050 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001051 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001052 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1053 QualType PrivateType = PrivateVD->getType();
1054 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1055 if (needCleanups(N)) {
1056 PrivateAddr = CGF.Builder.CreateElementBitCast(
1057 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1058 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1059 }
1060}
1061
1062static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1063 LValue BaseLV) {
1064 BaseTy = BaseTy.getNonReferenceType();
1065 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1066 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001067 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001068 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001069 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001070 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1071 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001072 }
1073 BaseTy = BaseTy->getPointeeType();
1074 }
1075 return CGF.MakeAddrLValue(
1076 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1077 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001078 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001079 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001080}
1081
1082static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1083 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1084 llvm::Value *Addr) {
1085 Address Tmp = Address::invalid();
1086 Address TopTmp = Address::invalid();
1087 Address MostTopTmp = Address::invalid();
1088 BaseTy = BaseTy.getNonReferenceType();
1089 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1090 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1091 Tmp = CGF.CreateMemTemp(BaseTy);
1092 if (TopTmp.isValid())
1093 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1094 else
1095 MostTopTmp = Tmp;
1096 TopTmp = Tmp;
1097 BaseTy = BaseTy->getPointeeType();
1098 }
1099 llvm::Type *Ty = BaseLVType;
1100 if (Tmp.isValid())
1101 Ty = Tmp.getElementType();
1102 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1103 if (Tmp.isValid()) {
1104 CGF.Builder.CreateStore(Addr, Tmp);
1105 return MostTopTmp;
1106 }
1107 return Address(Addr, BaseLVAlignment);
1108}
1109
Alexey Bataev1c44e152018-03-06 18:59:43 +00001110static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001111 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001112 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1113 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1114 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001115 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001116 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001117 Base = TempASE->getBase()->IgnoreParenImpCasts();
1118 DE = cast<DeclRefExpr>(Base);
1119 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001120 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1121 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1122 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001123 Base = TempASE->getBase()->IgnoreParenImpCasts();
1124 DE = cast<DeclRefExpr>(Base);
1125 OrigVD = cast<VarDecl>(DE->getDecl());
1126 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001127 return OrigVD;
1128}
1129
1130Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1131 Address PrivateAddr) {
1132 const DeclRefExpr *DE;
1133 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001134 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001135 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001136 LValue BaseLValue =
1137 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1138 OriginalBaseLValue);
1139 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1140 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001141 llvm::Value *PrivatePointer =
1142 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1143 PrivateAddr.getPointer(),
1144 SharedAddresses[N].first.getAddress().getType());
1145 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001146 return castToBase(CGF, OrigVD->getType(),
1147 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001148 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001149 OriginalBaseLValue.getAlignment(), Ptr);
1150 }
1151 BaseDecls.emplace_back(
1152 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1153 return PrivateAddr;
1154}
1155
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001156bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001157 const OMPDeclareReductionDecl *DRD =
1158 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001159 return DRD && DRD->getInitializer();
1160}
1161
Alexey Bataev18095712014-10-10 12:19:54 +00001162LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001163 return CGF.EmitLoadOfPointerLValue(
1164 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1165 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001166}
1167
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001168void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001169 if (!CGF.HaveInsertPoint())
1170 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001171 // 1.2.2 OpenMP Language Terminology
1172 // Structured block - An executable statement with a single entry at the
1173 // top and a single exit at the bottom.
1174 // The point of exit cannot be a branch out of the structured block.
1175 // longjmp() and throw() must not violate the entry/exit criteria.
1176 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001177 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001178 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001179}
1180
Alexey Bataev62b63b12015-03-10 07:28:44 +00001181LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1182 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001183 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1184 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001185 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001186}
1187
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001188static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1189 QualType FieldTy) {
1190 auto *Field = FieldDecl::Create(
1191 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1192 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1193 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1194 Field->setAccess(AS_public);
1195 DC->addDecl(Field);
1196 return Field;
1197}
1198
Alexey Bataev18fa2322018-05-02 14:20:50 +00001199CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1200 StringRef Separator)
1201 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1202 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001203 ASTContext &C = CGM.getContext();
1204 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1205 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1206 RD->startDefinition();
1207 // reserved_1
1208 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1209 // flags
1210 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1211 // reserved_2
1212 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1213 // reserved_3
1214 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1215 // psource
1216 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1217 RD->completeDefinition();
1218 IdentQTy = C.getRecordType(RD);
1219 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001220 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001221
1222 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001223}
1224
Alexey Bataev91797552015-03-18 04:13:55 +00001225void CGOpenMPRuntime::clear() {
1226 InternalVars.clear();
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00001227 // Clean non-target variable declarations possibly used only in debug info.
1228 for (const auto &Data : EmittedNonTargetVariables) {
1229 if (!Data.getValue().pointsToAliveValue())
1230 continue;
1231 auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
1232 if (!GV)
1233 continue;
1234 if (!GV->isDeclaration() || GV->getNumUses() > 0)
1235 continue;
1236 GV->eraseFromParent();
1237 }
Alexey Bataev91797552015-03-18 04:13:55 +00001238}
1239
Alexey Bataev18fa2322018-05-02 14:20:50 +00001240std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1241 SmallString<128> Buffer;
1242 llvm::raw_svector_ostream OS(Buffer);
1243 StringRef Sep = FirstSeparator;
1244 for (StringRef Part : Parts) {
1245 OS << Sep << Part;
1246 Sep = Separator;
1247 }
1248 return OS.str();
1249}
1250
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001251static llvm::Function *
1252emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1253 const Expr *CombinerInitializer, const VarDecl *In,
1254 const VarDecl *Out, bool IsCombiner) {
1255 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001256 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001257 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1258 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001259 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001260 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001261 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001262 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001263 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001264 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001265 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001266 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001267 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001268 std::string Name = CGM.getOpenMPRuntime().getName(
1269 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1270 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1271 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001272 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001273 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001274 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001275 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001276 CodeGenFunction CGF(CGM);
1277 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1278 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001279 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1280 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001281 CodeGenFunction::OMPPrivateScope Scope(CGF);
1282 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001283 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001284 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1285 .getAddress();
1286 });
1287 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001288 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001289 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1290 .getAddress();
1291 });
1292 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001293 if (!IsCombiner && Out->hasInit() &&
1294 !CGF.isTrivialInitializer(Out->getInit())) {
1295 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1296 Out->getType().getQualifiers(),
1297 /*IsInitializer=*/true);
1298 }
1299 if (CombinerInitializer)
1300 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001301 Scope.ForceCleanup();
1302 CGF.FinishFunction();
1303 return Fn;
1304}
1305
1306void CGOpenMPRuntime::emitUserDefinedReduction(
1307 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1308 if (UDRMap.count(D) > 0)
1309 return;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001310 llvm::Function *Combiner = emitCombinerOrInitializer(
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001311 CGM, D->getType(), D->getCombiner(),
1312 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1313 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001314 /*IsCombiner=*/true);
1315 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001316 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001317 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001318 CGM, D->getType(),
1319 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1320 : nullptr,
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001321 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1322 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001323 /*IsCombiner=*/false);
1324 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001325 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001326 if (CGF) {
1327 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1328 Decls.second.push_back(D);
1329 }
1330}
1331
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001332std::pair<llvm::Function *, llvm::Function *>
1333CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1334 auto I = UDRMap.find(D);
1335 if (I != UDRMap.end())
1336 return I->second;
1337 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1338 return UDRMap.lookup(D);
1339}
1340
James Y Knight9871db02019-02-05 16:42:33 +00001341static llvm::Function *emitParallelOrTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001342 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1343 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1344 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001345 assert(ThreadIDVar->getType()->isPointerType() &&
1346 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001347 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001348 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001349 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001350 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001351 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001352 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001353 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001354 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001355 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001356 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001357 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001358 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001359 else if (const auto *OPFD =
1360 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001361 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001362 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001363 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1364 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001365 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001366 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001367 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001368 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001369}
1370
James Y Knight9871db02019-02-05 16:42:33 +00001371llvm::Function *CGOpenMPRuntime::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001372 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1373 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1374 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1375 return emitParallelOrTeamsOutlinedFunction(
1376 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1377}
1378
James Y Knight9871db02019-02-05 16:42:33 +00001379llvm::Function *CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001380 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1381 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1382 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1383 return emitParallelOrTeamsOutlinedFunction(
1384 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1385}
1386
James Y Knight9871db02019-02-05 16:42:33 +00001387llvm::Function *CGOpenMPRuntime::emitTaskOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001388 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001389 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1390 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1391 bool Tied, unsigned &NumberOfParts) {
1392 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1393 PrePostActionTy &) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001394 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1395 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001396 llvm::Value *TaskArgs[] = {
1397 UpLoc, ThreadID,
1398 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1399 TaskTVar->getType()->castAs<PointerType>())
1400 .getPointer()};
1401 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1402 };
1403 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1404 UntiedCodeGen);
1405 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001406 assert(!ThreadIDVar->getType()->isPointerType() &&
1407 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001408 const OpenMPDirectiveKind Region =
1409 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1410 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001411 const CapturedStmt *CS = D.getCapturedStmt(Region);
1412 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001413 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001414 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1415 InnermostKind,
1416 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001417 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
James Y Knight9871db02019-02-05 16:42:33 +00001418 llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001419 if (!Tied)
1420 NumberOfParts = Action.getNumberOfParts();
1421 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001422}
1423
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001424static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1425 const RecordDecl *RD, const CGRecordLayout &RL,
1426 ArrayRef<llvm::Constant *> Data) {
1427 llvm::StructType *StructTy = RL.getLLVMType();
1428 unsigned PrevIdx = 0;
1429 ConstantInitBuilder CIBuilder(CGM);
1430 auto DI = Data.begin();
1431 for (const FieldDecl *FD : RD->fields()) {
1432 unsigned Idx = RL.getLLVMFieldNo(FD);
1433 // Fill the alignment.
1434 for (unsigned I = PrevIdx; I < Idx; ++I)
1435 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1436 PrevIdx = Idx + 1;
1437 Fields.add(*DI);
1438 ++DI;
1439 }
1440}
1441
1442template <class... As>
1443static llvm::GlobalVariable *
Mike Ricee1ca7b62018-08-29 15:45:11 +00001444createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
1445 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1446 As &&... Args) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001447 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1448 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1449 ConstantInitBuilder CIBuilder(CGM);
1450 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1451 buildStructValue(Fields, CGM, RD, RL, Data);
1452 return Fields.finishAndCreateGlobal(
Mike Ricee1ca7b62018-08-29 15:45:11 +00001453 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
1454 std::forward<As>(Args)...);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001455}
1456
1457template <typename T>
Benjamin Kramer651d0bf2018-05-15 21:26:47 +00001458static void
1459createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1460 ArrayRef<llvm::Constant *> Data,
1461 T &Parent) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001462 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1463 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1464 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1465 buildStructValue(Fields, CGM, RD, RL, Data);
1466 Fields.finishAndAddTo(Parent);
1467}
1468
Alexey Bataev50b3c952016-02-19 10:38:26 +00001469Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001470 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataevceeaa482018-11-21 21:04:34 +00001471 unsigned Reserved2Flags = getDefaultLocationReserved2Flags();
1472 FlagsTy FlagsKey(Flags, Reserved2Flags);
1473 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(FlagsKey);
Alexey Bataev9959db52014-05-06 10:08:46 +00001474 if (!Entry) {
1475 if (!DefaultOpenMPPSource) {
1476 // Initialize default location for psource field of ident_t structure of
1477 // all ident_t objects. Format is ";file;function;line;column;;".
1478 // Taken from
James Y Knight5d71fc52019-01-29 16:37:27 +00001479 // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp_str.cpp
Alexey Bataev9959db52014-05-06 10:08:46 +00001480 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001481 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001482 DefaultOpenMPPSource =
1483 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1484 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001485
Alexey Bataevceeaa482018-11-21 21:04:34 +00001486 llvm::Constant *Data[] = {
1487 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1488 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1489 llvm::ConstantInt::get(CGM.Int32Ty, Reserved2Flags),
1490 llvm::ConstantInt::getNullValue(CGM.Int32Ty), DefaultOpenMPPSource};
Mike Ricee1ca7b62018-08-29 15:45:11 +00001491 llvm::GlobalValue *DefaultOpenMPLocation =
Alexey Bataevceeaa482018-11-21 21:04:34 +00001492 createGlobalStruct(CGM, IdentQTy, isDefaultLocationConstant(), Data, "",
Mike Ricee1ca7b62018-08-29 15:45:11 +00001493 llvm::GlobalValue::PrivateLinkage);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001494 DefaultOpenMPLocation->setUnnamedAddr(
1495 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001496
Alexey Bataevceeaa482018-11-21 21:04:34 +00001497 OpenMPDefaultLocMap[FlagsKey] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001498 }
John McCall7f416cc2015-09-08 08:05:57 +00001499 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001500}
1501
Alexey Bataevfd006c42018-10-05 15:08:53 +00001502void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
1503 bool AtCurrentPoint) {
1504 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1505 assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
1506
1507 llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1508 if (AtCurrentPoint) {
1509 Elem.second.ServiceInsertPt = new llvm::BitCastInst(
1510 Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
1511 } else {
1512 Elem.second.ServiceInsertPt =
1513 new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1514 Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
1515 }
1516}
1517
1518void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
1519 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1520 if (Elem.second.ServiceInsertPt) {
1521 llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
1522 Elem.second.ServiceInsertPt = nullptr;
1523 Ptr->eraseFromParent();
1524 }
1525}
1526
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001527llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1528 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001529 unsigned Flags) {
1530 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001531 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001532 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001533 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001534 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001535
1536 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1537
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001538 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001539 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001540 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1541 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001542 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001543
Alexander Musmanc6388682014-12-15 07:07:06 +00001544 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1545 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001546 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001547 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001548 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001549 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001550 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001551 LocValue = AI;
1552
Alexey Bataevfd006c42018-10-05 15:08:53 +00001553 if (!Elem.second.ServiceInsertPt)
1554 setLocThreadIdInsertPt(CGF);
Alexey Bataev9959db52014-05-06 10:08:46 +00001555 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001556 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001557 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001558 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001559 }
1560
1561 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001562 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1563 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1564 LValue PSource =
1565 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001566
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001567 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001568 if (OMPDebugLoc == nullptr) {
1569 SmallString<128> Buffer2;
1570 llvm::raw_svector_ostream OS2(Buffer2);
1571 // Build debug location
1572 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1573 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001574 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001575 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001576 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1577 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1578 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001579 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001580 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001581 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001582
John McCall7f416cc2015-09-08 08:05:57 +00001583 // Our callers always pass this to a runtime function, so for
1584 // convenience, go ahead and return a naked pointer.
1585 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001586}
1587
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001588llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1589 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001590 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1591
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001592 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001593 // Check whether we've already cached a load of the thread id in this
1594 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001595 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001596 if (I != OpenMPLocThreadIDMap.end()) {
1597 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001598 if (ThreadID != nullptr)
1599 return ThreadID;
1600 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001601 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001602 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1603 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001604 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001605 if (auto *OMPRegionInfo =
1606 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1607 if (OMPRegionInfo->getThreadIDVariable()) {
1608 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001609 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001610 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001611 // If value loaded in entry block, cache it and use it everywhere in
1612 // function.
1613 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1614 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1615 Elem.second.ThreadID = ThreadID;
1616 }
1617 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001618 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001619 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001620 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001621
1622 // This is not an outlined function region - need to call __kmpc_int32
1623 // kmpc_global_thread_num(ident_t *loc).
1624 // Generate thread id value and cache this value for use across the
1625 // function.
Alexey Bataevfd006c42018-10-05 15:08:53 +00001626 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1627 if (!Elem.second.ServiceInsertPt)
1628 setLocThreadIdInsertPt(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001629 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001630 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001631 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001632 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1633 emitUpdateLocation(CGF, Loc));
1634 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001635 Elem.second.ThreadID = Call;
1636 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001637}
1638
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001639void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001640 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataevfd006c42018-10-05 15:08:53 +00001641 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1642 clearLocThreadIdInsertPt(CGF);
Alexey Bataev03b340a2014-10-21 03:16:40 +00001643 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001644 }
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001645 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001646 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001647 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001648 FunctionUDRMap.erase(CGF.CurFn);
1649 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001650}
1651
1652llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001653 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001654}
1655
1656llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001657 if (!Kmpc_MicroTy) {
1658 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1659 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1660 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1661 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1662 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001663 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1664}
1665
James Y Knight9871db02019-02-05 16:42:33 +00001666llvm::FunctionCallee CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
1667 llvm::FunctionCallee RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001668 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001669 case OMPRTL__kmpc_fork_call: {
1670 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1671 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1673 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001674 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001675 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001676 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
James Y Knight9871db02019-02-05 16:42:33 +00001677 if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
Johannes Doerfertac991bb2019-01-19 05:36:54 +00001678 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
1679 llvm::LLVMContext &Ctx = F->getContext();
1680 llvm::MDBuilder MDB(Ctx);
1681 // Annotate the callback behavior of the __kmpc_fork_call:
1682 // - The callback callee is argument number 2 (microtask).
1683 // - The first two arguments of the callback callee are unknown (-1).
1684 // - All variadic arguments to the __kmpc_fork_call are passed to the
1685 // callback callee.
1686 F->addMetadata(
1687 llvm::LLVMContext::MD_callback,
1688 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1689 2, {-1, -1},
1690 /* VarArgsArePassed */ true)}));
1691 }
1692 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001693 break;
1694 }
1695 case OMPRTL__kmpc_global_thread_num: {
1696 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001697 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001698 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001699 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001700 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1701 break;
1702 }
Alexey Bataev97720002014-11-11 04:05:39 +00001703 case OMPRTL__kmpc_threadprivate_cached: {
1704 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1705 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1706 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1707 CGM.VoidPtrTy, CGM.SizeTy,
1708 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001709 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001710 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1711 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1712 break;
1713 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001714 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001715 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1716 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001717 llvm::Type *TypeParams[] = {
1718 getIdentTyPointerTy(), CGM.Int32Ty,
1719 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001720 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001721 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1722 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1723 break;
1724 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001725 case OMPRTL__kmpc_critical_with_hint: {
1726 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1727 // kmp_critical_name *crit, uintptr_t hint);
1728 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1729 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1730 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001731 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001732 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1733 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1734 break;
1735 }
Alexey Bataev97720002014-11-11 04:05:39 +00001736 case OMPRTL__kmpc_threadprivate_register: {
1737 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1738 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1739 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001740 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001741 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1742 /*isVarArg*/ false)->getPointerTo();
1743 // typedef void *(*kmpc_cctor)(void *, void *);
1744 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001745 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001746 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001747 /*isVarArg*/ false)
1748 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001749 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001750 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001751 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1752 ->getPointerTo();
1753 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1754 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001755 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001756 /*isVarArg*/ false);
1757 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1758 break;
1759 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001760 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001761 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1762 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001763 llvm::Type *TypeParams[] = {
1764 getIdentTyPointerTy(), CGM.Int32Ty,
1765 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001766 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001767 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1768 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1769 break;
1770 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001771 case OMPRTL__kmpc_cancel_barrier: {
1772 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1773 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001775 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001776 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001778 break;
1779 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001780 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001781 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001782 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001783 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1785 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1786 break;
1787 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001788 case OMPRTL__kmpc_for_static_fini: {
1789 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1790 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001791 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001792 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1793 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1794 break;
1795 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001796 case OMPRTL__kmpc_push_num_threads: {
1797 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1798 // kmp_int32 num_threads)
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1800 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001801 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001802 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1803 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1804 break;
1805 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001806 case OMPRTL__kmpc_serialized_parallel: {
1807 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1808 // global_tid);
1809 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001810 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001811 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1812 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1813 break;
1814 }
1815 case OMPRTL__kmpc_end_serialized_parallel: {
1816 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1817 // global_tid);
1818 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001819 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001820 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1821 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1822 break;
1823 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001824 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001825 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001826 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001827 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001828 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001829 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1830 break;
1831 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001832 case OMPRTL__kmpc_master: {
1833 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1834 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001835 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001836 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1837 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1838 break;
1839 }
1840 case OMPRTL__kmpc_end_master: {
1841 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1842 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001843 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001844 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1845 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1846 break;
1847 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001848 case OMPRTL__kmpc_omp_taskyield: {
1849 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1850 // int end_part);
1851 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001852 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001853 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1854 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1855 break;
1856 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001857 case OMPRTL__kmpc_single: {
1858 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1859 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001860 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001861 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1862 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1863 break;
1864 }
1865 case OMPRTL__kmpc_end_single: {
1866 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1867 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001868 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001869 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1870 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1871 break;
1872 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001873 case OMPRTL__kmpc_omp_task_alloc: {
1874 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1875 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1876 // kmp_routine_entry_t *task_entry);
1877 assert(KmpRoutineEntryPtrTy != nullptr &&
1878 "Type kmp_routine_entry_t must be created.");
1879 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1880 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1881 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001882 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001883 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1884 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1885 break;
1886 }
1887 case OMPRTL__kmpc_omp_task: {
1888 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1889 // *new_task);
1890 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1891 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001892 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001893 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1894 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1895 break;
1896 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001897 case OMPRTL__kmpc_copyprivate: {
1898 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001899 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001900 // kmp_int32 didit);
1901 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1902 auto *CpyFnTy =
1903 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001904 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001905 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1906 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001907 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001908 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1909 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1910 break;
1911 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001912 case OMPRTL__kmpc_reduce: {
1913 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1914 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1915 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1916 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1917 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1918 /*isVarArg=*/false);
1919 llvm::Type *TypeParams[] = {
1920 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1921 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1922 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001923 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001924 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1925 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1926 break;
1927 }
1928 case OMPRTL__kmpc_reduce_nowait: {
1929 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1930 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1931 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1932 // *lck);
1933 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1934 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1935 /*isVarArg=*/false);
1936 llvm::Type *TypeParams[] = {
1937 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1938 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1939 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001940 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001941 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1942 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1943 break;
1944 }
1945 case OMPRTL__kmpc_end_reduce: {
1946 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1947 // kmp_critical_name *lck);
1948 llvm::Type *TypeParams[] = {
1949 getIdentTyPointerTy(), CGM.Int32Ty,
1950 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001951 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001952 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1953 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1954 break;
1955 }
1956 case OMPRTL__kmpc_end_reduce_nowait: {
1957 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1958 // kmp_critical_name *lck);
1959 llvm::Type *TypeParams[] = {
1960 getIdentTyPointerTy(), CGM.Int32Ty,
1961 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001962 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001963 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1964 RTLFn =
1965 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1966 break;
1967 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001968 case OMPRTL__kmpc_omp_task_begin_if0: {
1969 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1970 // *new_task);
1971 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1972 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001973 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001974 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1975 RTLFn =
1976 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1977 break;
1978 }
1979 case OMPRTL__kmpc_omp_task_complete_if0: {
1980 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1981 // *new_task);
1982 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1983 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001984 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001985 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1986 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1987 /*Name=*/"__kmpc_omp_task_complete_if0");
1988 break;
1989 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001990 case OMPRTL__kmpc_ordered: {
1991 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1992 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001993 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001994 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1995 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1996 break;
1997 }
1998 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001999 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002000 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002001 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002002 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2003 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
2004 break;
2005 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002006 case OMPRTL__kmpc_omp_taskwait: {
2007 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
2008 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002009 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002010 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2011 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
2012 break;
2013 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002014 case OMPRTL__kmpc_taskgroup: {
2015 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
2016 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002017 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002018 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2019 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
2020 break;
2021 }
2022 case OMPRTL__kmpc_end_taskgroup: {
2023 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
2024 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002025 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002026 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2027 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
2028 break;
2029 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00002030 case OMPRTL__kmpc_push_proc_bind: {
2031 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
2032 // int proc_bind)
2033 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002034 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002035 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2036 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2037 break;
2038 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002039 case OMPRTL__kmpc_omp_task_with_deps: {
2040 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2041 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2042 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2043 llvm::Type *TypeParams[] = {
2044 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2045 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002046 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002047 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2048 RTLFn =
2049 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2050 break;
2051 }
2052 case OMPRTL__kmpc_omp_wait_deps: {
2053 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2054 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2055 // kmp_depend_info_t *noalias_dep_list);
2056 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2057 CGM.Int32Ty, CGM.VoidPtrTy,
2058 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002059 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002060 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2061 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2062 break;
2063 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002064 case OMPRTL__kmpc_cancellationpoint: {
2065 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2066 // global_tid, kmp_int32 cncl_kind)
2067 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002068 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002069 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2070 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2071 break;
2072 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002073 case OMPRTL__kmpc_cancel: {
2074 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2075 // kmp_int32 cncl_kind)
2076 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002077 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002078 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2079 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2080 break;
2081 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002082 case OMPRTL__kmpc_push_num_teams: {
2083 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2084 // kmp_int32 num_teams, kmp_int32 num_threads)
2085 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2086 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002087 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002088 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2089 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2090 break;
2091 }
2092 case OMPRTL__kmpc_fork_teams: {
2093 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2094 // microtask, ...);
2095 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2096 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002097 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002098 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2099 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
James Y Knight9871db02019-02-05 16:42:33 +00002100 if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002101 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
2102 llvm::LLVMContext &Ctx = F->getContext();
2103 llvm::MDBuilder MDB(Ctx);
2104 // Annotate the callback behavior of the __kmpc_fork_teams:
2105 // - The callback callee is argument number 2 (microtask).
2106 // - The first two arguments of the callback callee are unknown (-1).
2107 // - All variadic arguments to the __kmpc_fork_teams are passed to the
2108 // callback callee.
2109 F->addMetadata(
2110 llvm::LLVMContext::MD_callback,
2111 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2112 2, {-1, -1},
2113 /* VarArgsArePassed */ true)}));
2114 }
2115 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002116 break;
2117 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002118 case OMPRTL__kmpc_taskloop: {
2119 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2120 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2121 // sched, kmp_uint64 grainsize, void *task_dup);
2122 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2123 CGM.IntTy,
2124 CGM.VoidPtrTy,
2125 CGM.IntTy,
2126 CGM.Int64Ty->getPointerTo(),
2127 CGM.Int64Ty->getPointerTo(),
2128 CGM.Int64Ty,
2129 CGM.IntTy,
2130 CGM.IntTy,
2131 CGM.Int64Ty,
2132 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002133 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002134 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2135 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2136 break;
2137 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002138 case OMPRTL__kmpc_doacross_init: {
2139 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2140 // num_dims, struct kmp_dim *dims);
2141 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2142 CGM.Int32Ty,
2143 CGM.Int32Ty,
2144 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002145 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002146 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2147 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2148 break;
2149 }
2150 case OMPRTL__kmpc_doacross_fini: {
2151 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2152 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002153 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002154 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2155 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2156 break;
2157 }
2158 case OMPRTL__kmpc_doacross_post: {
2159 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2160 // *vec);
2161 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2162 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002163 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002164 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2165 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2166 break;
2167 }
2168 case OMPRTL__kmpc_doacross_wait: {
2169 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2170 // *vec);
2171 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2172 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002173 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002174 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2175 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2176 break;
2177 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002178 case OMPRTL__kmpc_task_reduction_init: {
2179 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2180 // *data);
2181 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002182 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002183 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2184 RTLFn =
2185 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2186 break;
2187 }
2188 case OMPRTL__kmpc_task_reduction_get_th_data: {
2189 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2190 // *d);
2191 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002192 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002193 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2194 RTLFn = CGM.CreateRuntimeFunction(
2195 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2196 break;
2197 }
Alexey Bataev7bb33532019-01-07 21:30:43 +00002198 case OMPRTL__kmpc_push_target_tripcount: {
2199 // Build void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
2200 // size);
2201 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int64Ty};
2202 llvm::FunctionType *FnTy =
2203 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2204 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_target_tripcount");
2205 break;
2206 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002207 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002208 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2209 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002210 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002211 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002212 CGM.VoidPtrTy,
2213 CGM.Int32Ty,
2214 CGM.VoidPtrPtrTy,
2215 CGM.VoidPtrPtrTy,
2216 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002217 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002218 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002219 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2220 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2221 break;
2222 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002223 case OMPRTL__tgt_target_nowait: {
2224 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2225 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2226 // int64_t *arg_types);
2227 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2228 CGM.VoidPtrTy,
2229 CGM.Int32Ty,
2230 CGM.VoidPtrPtrTy,
2231 CGM.VoidPtrPtrTy,
2232 CGM.SizeTy->getPointerTo(),
2233 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002234 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002235 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2236 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2237 break;
2238 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002239 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002240 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002241 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002242 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2243 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002244 CGM.VoidPtrTy,
2245 CGM.Int32Ty,
2246 CGM.VoidPtrPtrTy,
2247 CGM.VoidPtrPtrTy,
2248 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002249 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002250 CGM.Int32Ty,
2251 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002252 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002253 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2254 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2255 break;
2256 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002257 case OMPRTL__tgt_target_teams_nowait: {
2258 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2259 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2260 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2261 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2262 CGM.VoidPtrTy,
2263 CGM.Int32Ty,
2264 CGM.VoidPtrPtrTy,
2265 CGM.VoidPtrPtrTy,
2266 CGM.SizeTy->getPointerTo(),
2267 CGM.Int64Ty->getPointerTo(),
2268 CGM.Int32Ty,
2269 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002270 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002271 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2272 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2273 break;
2274 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002275 case OMPRTL__tgt_register_lib: {
2276 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2277 QualType ParamTy =
2278 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2279 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002280 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002281 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2282 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2283 break;
2284 }
2285 case OMPRTL__tgt_unregister_lib: {
2286 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2287 QualType ParamTy =
2288 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2289 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002290 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002291 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2292 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2293 break;
2294 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002295 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002296 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2297 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2298 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002299 CGM.Int32Ty,
2300 CGM.VoidPtrPtrTy,
2301 CGM.VoidPtrPtrTy,
2302 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002303 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002304 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002305 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2306 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2307 break;
2308 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002309 case OMPRTL__tgt_target_data_begin_nowait: {
2310 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2311 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2312 // *arg_types);
2313 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2314 CGM.Int32Ty,
2315 CGM.VoidPtrPtrTy,
2316 CGM.VoidPtrPtrTy,
2317 CGM.SizeTy->getPointerTo(),
2318 CGM.Int64Ty->getPointerTo()};
2319 auto *FnTy =
2320 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2321 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2322 break;
2323 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002324 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002325 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2326 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2327 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002328 CGM.Int32Ty,
2329 CGM.VoidPtrPtrTy,
2330 CGM.VoidPtrPtrTy,
2331 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002332 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002333 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002334 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2335 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2336 break;
2337 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002338 case OMPRTL__tgt_target_data_end_nowait: {
2339 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2340 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2341 // *arg_types);
2342 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2343 CGM.Int32Ty,
2344 CGM.VoidPtrPtrTy,
2345 CGM.VoidPtrPtrTy,
2346 CGM.SizeTy->getPointerTo(),
2347 CGM.Int64Ty->getPointerTo()};
2348 auto *FnTy =
2349 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2350 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2351 break;
2352 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002353 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002354 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2355 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2356 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002357 CGM.Int32Ty,
2358 CGM.VoidPtrPtrTy,
2359 CGM.VoidPtrPtrTy,
2360 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002361 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002362 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002363 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2364 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2365 break;
2366 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002367 case OMPRTL__tgt_target_data_update_nowait: {
2368 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2369 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2370 // *arg_types);
2371 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2372 CGM.Int32Ty,
2373 CGM.VoidPtrPtrTy,
2374 CGM.VoidPtrPtrTy,
2375 CGM.SizeTy->getPointerTo(),
2376 CGM.Int64Ty->getPointerTo()};
2377 auto *FnTy =
2378 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2379 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2380 break;
2381 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002382 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002383 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002384 return RTLFn;
2385}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002386
James Y Knight9871db02019-02-05 16:42:33 +00002387llvm::FunctionCallee
2388CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, bool IVSigned) {
Alexander Musman21212e42015-03-13 10:38:23 +00002389 assert((IVSize == 32 || IVSize == 64) &&
2390 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002391 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2392 : "__kmpc_for_static_init_4u")
2393 : (IVSigned ? "__kmpc_for_static_init_8"
2394 : "__kmpc_for_static_init_8u");
2395 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2396 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002397 llvm::Type *TypeParams[] = {
2398 getIdentTyPointerTy(), // loc
2399 CGM.Int32Ty, // tid
2400 CGM.Int32Ty, // schedtype
2401 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2402 PtrTy, // p_lower
2403 PtrTy, // p_upper
2404 PtrTy, // p_stride
2405 ITy, // incr
2406 ITy // chunk
2407 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002408 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002409 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2410 return CGM.CreateRuntimeFunction(FnTy, Name);
2411}
2412
James Y Knight9871db02019-02-05 16:42:33 +00002413llvm::FunctionCallee
2414CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002415 assert((IVSize == 32 || IVSize == 64) &&
2416 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002417 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002418 IVSize == 32
2419 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2420 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002421 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002422 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2423 CGM.Int32Ty, // tid
2424 CGM.Int32Ty, // schedtype
2425 ITy, // lower
2426 ITy, // upper
2427 ITy, // stride
2428 ITy // chunk
2429 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002430 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002431 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2432 return CGM.CreateRuntimeFunction(FnTy, Name);
2433}
2434
James Y Knight9871db02019-02-05 16:42:33 +00002435llvm::FunctionCallee
2436CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002437 assert((IVSize == 32 || IVSize == 64) &&
2438 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002439 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002440 IVSize == 32
2441 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2442 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2443 llvm::Type *TypeParams[] = {
2444 getIdentTyPointerTy(), // loc
2445 CGM.Int32Ty, // tid
2446 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002447 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002448 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2449 return CGM.CreateRuntimeFunction(FnTy, Name);
2450}
2451
James Y Knight9871db02019-02-05 16:42:33 +00002452llvm::FunctionCallee
2453CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002454 assert((IVSize == 32 || IVSize == 64) &&
2455 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002456 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002457 IVSize == 32
2458 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2459 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002460 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2461 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002462 llvm::Type *TypeParams[] = {
2463 getIdentTyPointerTy(), // loc
2464 CGM.Int32Ty, // tid
2465 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2466 PtrTy, // p_lower
2467 PtrTy, // p_upper
2468 PtrTy // p_stride
2469 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002470 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002471 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2472 return CGM.CreateRuntimeFunction(FnTy, Name);
2473}
2474
Alexey Bataev03f270c2018-03-30 18:31:07 +00002475Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2476 if (CGM.getLangOpts().OpenMPSimd)
2477 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002478 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002479 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002480 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2481 SmallString<64> PtrName;
2482 {
2483 llvm::raw_svector_ostream OS(PtrName);
2484 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2485 }
2486 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2487 if (!Ptr) {
2488 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2489 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2490 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002491 if (!CGM.getLangOpts().OpenMPIsDevice) {
2492 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2493 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2494 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2495 }
2496 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2497 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002498 }
2499 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2500 }
2501 return Address::invalid();
2502}
2503
Alexey Bataev97720002014-11-11 04:05:39 +00002504llvm::Constant *
2505CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002506 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2507 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002508 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002509 std::string Suffix = getName({"cache", ""});
2510 return getOrCreateInternalVariable(
2511 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002512}
2513
John McCall7f416cc2015-09-08 08:05:57 +00002514Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2515 const VarDecl *VD,
2516 Address VDAddr,
2517 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002518 if (CGM.getLangOpts().OpenMPUseTLS &&
2519 CGM.getContext().getTargetInfo().isTLSSupported())
2520 return VDAddr;
2521
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002522 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002523 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002524 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2525 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002526 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2527 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002528 return Address(CGF.EmitRuntimeCall(
2529 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2530 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002531}
2532
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002533void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002534 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002535 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2536 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2537 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002538 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002539 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002540 OMPLoc);
2541 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2542 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002543 llvm::Value *Args[] = {
2544 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2545 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002546 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002547 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002548}
2549
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002550llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002551 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002552 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002553 if (CGM.getLangOpts().OpenMPUseTLS &&
2554 CGM.getContext().getTargetInfo().isTLSSupported())
2555 return nullptr;
2556
Alexey Bataev97720002014-11-11 04:05:39 +00002557 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002558 if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
Alexey Bataev97720002014-11-11 04:05:39 +00002559 QualType ASTTy = VD->getType();
2560
2561 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002562 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002563 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2564 // Generate function that re-emits the declaration's initializer into the
2565 // threadprivate copy of the variable VD
2566 CodeGenFunction CtorCGF(CGM);
2567 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002568 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2569 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002570 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002571 Args.push_back(&Dst);
2572
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002573 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002574 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002575 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002576 std::string Name = getName({"__kmpc_global_ctor_", ""});
2577 llvm::Function *Fn =
2578 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002579 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002580 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002581 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002582 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002583 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002584 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002585 Arg = CtorCGF.Builder.CreateElementBitCast(
2586 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002587 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2588 /*IsInitializer=*/true);
2589 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002590 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002591 CGM.getContext().VoidPtrTy, Dst.getLocation());
2592 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2593 CtorCGF.FinishFunction();
2594 Ctor = Fn;
2595 }
2596 if (VD->getType().isDestructedType() != QualType::DK_none) {
2597 // Generate function that emits destructor call for the threadprivate copy
2598 // of the variable VD
2599 CodeGenFunction DtorCGF(CGM);
2600 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002601 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2602 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002603 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002604 Args.push_back(&Dst);
2605
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002606 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002607 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002608 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002609 std::string Name = getName({"__kmpc_global_dtor_", ""});
2610 llvm::Function *Fn =
2611 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002612 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002613 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002614 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002615 // Create a scope with an artificial location for the body of this function.
2616 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002617 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002618 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002619 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2620 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002621 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2622 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2623 DtorCGF.FinishFunction();
2624 Dtor = Fn;
2625 }
2626 // Do not emit init function if it is not required.
2627 if (!Ctor && !Dtor)
2628 return nullptr;
2629
2630 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002631 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2632 /*isVarArg=*/false)
2633 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002634 // Copying constructor for the threadprivate variable.
2635 // Must be NULL - reserved by runtime, but currently it requires that this
2636 // parameter is always NULL. Otherwise it fires assertion.
2637 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2638 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002639 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2640 /*isVarArg=*/false)
2641 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002642 Ctor = llvm::Constant::getNullValue(CtorTy);
2643 }
2644 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002645 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2646 /*isVarArg=*/false)
2647 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002648 Dtor = llvm::Constant::getNullValue(DtorTy);
2649 }
2650 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002651 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002652 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002653 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002654 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002655 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002656 CodeGenFunction InitCGF(CGM);
2657 FunctionArgList ArgList;
2658 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2659 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002660 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002661 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002662 InitCGF.FinishFunction();
2663 return InitFunction;
2664 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002665 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002666 }
2667 return nullptr;
2668}
2669
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002670/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002671/// consists of the file and device IDs as well as line number associated with
2672/// the relevant entry source location.
2673static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2674 unsigned &DeviceID, unsigned &FileID,
2675 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002676 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002677
2678 // The loc should be always valid and have a file ID (the user cannot use
2679 // #pragma directives in macros)
2680
2681 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002682
2683 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2684 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2685
2686 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002687 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2688 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2689 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002690
2691 DeviceID = ID.getDevice();
2692 FileID = ID.getFile();
2693 LineNum = PLoc.getLine();
2694}
2695
2696bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2697 llvm::GlobalVariable *Addr,
2698 bool PerformInit) {
2699 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002700 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002701 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
Alexey Bataevd01b7492018-08-15 19:45:12 +00002702 return CGM.getLangOpts().OpenMPIsDevice;
Alexey Bataev34f8a702018-03-28 14:28:54 +00002703 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002704 if (VD && !DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
Alexey Bataev34f8a702018-03-28 14:28:54 +00002705 return CGM.getLangOpts().OpenMPIsDevice;
2706
2707 QualType ASTTy = VD->getType();
2708
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002709 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002710 // Produce the unique prefix to identify the new target regions. We use
2711 // the source location of the variable declaration which we know to not
2712 // conflict with any target region.
2713 unsigned DeviceID;
2714 unsigned FileID;
2715 unsigned Line;
2716 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2717 SmallString<128> Buffer, Out;
2718 {
2719 llvm::raw_svector_ostream OS(Buffer);
2720 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2721 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2722 }
2723
2724 const Expr *Init = VD->getAnyInitializer();
2725 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2726 llvm::Constant *Ctor;
2727 llvm::Constant *ID;
2728 if (CGM.getLangOpts().OpenMPIsDevice) {
2729 // Generate function that re-emits the declaration's initializer into
2730 // the threadprivate copy of the variable VD
2731 CodeGenFunction CtorCGF(CGM);
2732
2733 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2734 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2735 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2736 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2737 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2738 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2739 FunctionArgList(), Loc, Loc);
2740 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2741 CtorCGF.EmitAnyExprToMem(Init,
2742 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2743 Init->getType().getQualifiers(),
2744 /*IsInitializer=*/true);
2745 CtorCGF.FinishFunction();
2746 Ctor = Fn;
2747 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002748 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002749 } else {
2750 Ctor = new llvm::GlobalVariable(
2751 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2752 llvm::GlobalValue::PrivateLinkage,
2753 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2754 ID = Ctor;
2755 }
2756
2757 // Register the information for the entry associated with the constructor.
2758 Out.clear();
2759 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2760 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002761 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002762 }
2763 if (VD->getType().isDestructedType() != QualType::DK_none) {
2764 llvm::Constant *Dtor;
2765 llvm::Constant *ID;
2766 if (CGM.getLangOpts().OpenMPIsDevice) {
2767 // Generate function that emits destructor call for the threadprivate
2768 // copy of the variable VD
2769 CodeGenFunction DtorCGF(CGM);
2770
2771 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2772 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2773 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2774 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2775 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2776 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2777 FunctionArgList(), Loc, Loc);
2778 // Create a scope with an artificial location for the body of this
2779 // function.
2780 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2781 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2782 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2783 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2784 DtorCGF.FinishFunction();
2785 Dtor = Fn;
2786 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002787 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002788 } else {
2789 Dtor = new llvm::GlobalVariable(
2790 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2791 llvm::GlobalValue::PrivateLinkage,
2792 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2793 ID = Dtor;
2794 }
2795 // Register the information for the entry associated with the destructor.
2796 Out.clear();
2797 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2798 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002799 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002800 }
2801 return CGM.getLangOpts().OpenMPIsDevice;
2802}
2803
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002804Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2805 QualType VarType,
2806 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002807 std::string Suffix = getName({"artificial", ""});
2808 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002809 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002810 llvm::Value *GAddr =
2811 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002812 llvm::Value *Args[] = {
2813 emitUpdateLocation(CGF, SourceLocation()),
2814 getThreadID(CGF, SourceLocation()),
2815 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2816 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2817 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002818 getOrCreateInternalVariable(
2819 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002820 return Address(
2821 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2822 CGF.EmitRuntimeCall(
2823 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2824 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2825 CGM.getPointerAlign());
2826}
2827
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002828void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2829 const RegionCodeGenTy &ThenGen,
2830 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002831 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2832
2833 // If the condition constant folds and can be elided, try to avoid emitting
2834 // the condition and the dead arm of the if/else.
2835 bool CondConstant;
2836 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002837 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002838 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002839 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002840 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002841 return;
2842 }
2843
2844 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2845 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002846 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2847 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2848 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002849 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2850
2851 // Emit the 'then' code.
2852 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002853 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002854 CGF.EmitBranch(ContBlock);
2855 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002856 // There is no need to emit line number for unconditional branch.
2857 (void)ApplyDebugLocation::CreateEmpty(CGF);
2858 CGF.EmitBlock(ElseBlock);
2859 ElseGen(CGF);
2860 // There is no need to emit line number for unconditional branch.
2861 (void)ApplyDebugLocation::CreateEmpty(CGF);
2862 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002863 // Emit the continuation block for code after the if.
2864 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002865}
2866
Alexey Bataev1d677132015-04-22 13:57:31 +00002867void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002868 llvm::Function *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002869 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002870 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002871 if (!CGF.HaveInsertPoint())
2872 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002873 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002874 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2875 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002876 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002877 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002878 llvm::Value *Args[] = {
2879 RTLoc,
2880 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002881 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002882 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2883 RealArgs.append(std::begin(Args), std::end(Args));
2884 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2885
James Y Knight9871db02019-02-05 16:42:33 +00002886 llvm::FunctionCallee RTLFn =
2887 RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002888 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2889 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002890 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2891 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002892 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2893 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002894 // Build calls:
2895 // __kmpc_serialized_parallel(&Loc, GTid);
2896 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002897 CGF.EmitRuntimeCall(
2898 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002899
Alexey Bataev1d677132015-04-22 13:57:31 +00002900 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002901 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2902 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002903 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002904 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataev8521ff62018-07-25 20:03:01 +00002905 // ThreadId for serialized parallels is 0.
2906 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002907 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2908 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002909 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002910
Alexey Bataev1d677132015-04-22 13:57:31 +00002911 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002912 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002913 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002914 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2915 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002916 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002917 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002918 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002919 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002920 RegionCodeGenTy ThenRCG(ThenGen);
2921 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002922 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002923}
2924
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002925// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002926// thread-ID variable (it is passed in a first argument of the outlined function
2927// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2928// regular serial code region, get thread ID by calling kmp_int32
2929// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2930// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002931Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2932 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002933 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002934 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002935 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002936 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002937
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002938 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2939 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002940 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002941 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002942 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002943 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002944
2945 return ThreadIDTemp;
2946}
2947
Alexey Bataev1af5bd52019-03-05 17:47:18 +00002948llvm::Constant *CGOpenMPRuntime::getOrCreateInternalVariable(
2949 llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002950 SmallString<256> Buffer;
2951 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002952 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002953 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002954 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002955 if (Elem.second) {
2956 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002957 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002958 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002959 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002960
David Blaikie13156b62014-11-19 03:06:06 +00002961 return Elem.second = new llvm::GlobalVariable(
2962 CGM.getModule(), Ty, /*IsConstant*/ false,
2963 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
Alexey Bataev1af5bd52019-03-05 17:47:18 +00002964 Elem.first(), /*InsertBefore=*/nullptr,
2965 llvm::GlobalValue::NotThreadLocal, AddressSpace);
Alexey Bataev97720002014-11-11 04:05:39 +00002966}
2967
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002968llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002969 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2970 std::string Name = getName({Prefix, "var"});
2971 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002972}
2973
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002974namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002975/// Common pre(post)-action for different OpenMP constructs.
2976class CommonActionTy final : public PrePostActionTy {
James Y Knight9871db02019-02-05 16:42:33 +00002977 llvm::FunctionCallee EnterCallee;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002978 ArrayRef<llvm::Value *> EnterArgs;
James Y Knight9871db02019-02-05 16:42:33 +00002979 llvm::FunctionCallee ExitCallee;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002980 ArrayRef<llvm::Value *> ExitArgs;
2981 bool Conditional;
2982 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002983
2984public:
James Y Knight9871db02019-02-05 16:42:33 +00002985 CommonActionTy(llvm::FunctionCallee EnterCallee,
2986 ArrayRef<llvm::Value *> EnterArgs,
2987 llvm::FunctionCallee ExitCallee,
2988 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002989 : 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.
James Y Knight751fe282019-02-09 22:22:28 +00003093 Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index);
John McCall7f416cc2015-09-08 08:05:57 +00003094 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3095
3096 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003097 Addr = CGF.Builder.CreateElementBitCast(
3098 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003099 return Addr;
3100}
3101
Alexey Bataeva63048e2015-03-23 06:18:07 +00003102static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003103 CodeGenModule &CGM, llvm::Type *ArgsType,
3104 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003105 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3106 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003107 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003108 // void copy_func(void *LHSArg, void *RHSArg);
3109 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003110 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3111 ImplicitParamDecl::Other);
3112 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3113 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003114 Args.push_back(&LHSArg);
3115 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003116 const auto &CGFI =
3117 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003118 std::string Name =
3119 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3120 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3121 llvm::GlobalValue::InternalLinkage, Name,
3122 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003123 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003124 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003125 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003126 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003127 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003128 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003129 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3130 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3131 ArgsType), CGF.getPointerAlign());
3132 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3133 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3134 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003135 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3136 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3137 // ...
3138 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003139 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003140 const auto *DestVar =
3141 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003142 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3143
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003144 const auto *SrcVar =
3145 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003146 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3147
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003148 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003149 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003150 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003151 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003152 CGF.FinishFunction();
3153 return Fn;
3154}
3155
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003156void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003157 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003158 SourceLocation Loc,
3159 ArrayRef<const Expr *> CopyprivateVars,
3160 ArrayRef<const Expr *> SrcExprs,
3161 ArrayRef<const Expr *> DstExprs,
3162 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003163 if (!CGF.HaveInsertPoint())
3164 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003165 assert(CopyprivateVars.size() == SrcExprs.size() &&
3166 CopyprivateVars.size() == DstExprs.size() &&
3167 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003168 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003169 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003170 // if(__kmpc_single(ident_t *, gtid)) {
3171 // SingleOpGen();
3172 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003173 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003174 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003175 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3176 // <copy_func>, did_it);
3177
John McCall7f416cc2015-09-08 08:05:57 +00003178 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003179 if (!CopyprivateVars.empty()) {
3180 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003181 QualType KmpInt32Ty =
3182 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003183 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003184 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003185 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003186 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003187 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003188 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3189 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3190 /*Conditional=*/true);
3191 SingleOpGen.setAction(Action);
3192 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3193 if (DidIt.isValid()) {
3194 // did_it = 1;
3195 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3196 }
3197 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003198 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3199 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003200 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003201 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003202 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003203 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3204 /*IndexTypeQuals=*/0);
3205 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003206 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003207 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3208 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
James Y Knight751fe282019-02-09 22:22:28 +00003209 Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I);
John McCall7f416cc2015-09-08 08:05:57 +00003210 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003211 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003212 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3213 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003214 }
3215 // Build function that copies private values from single region to all other
3216 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003217 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003218 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003219 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003220 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003221 Address CL =
3222 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3223 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003224 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003225 llvm::Value *Args[] = {
3226 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3227 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003228 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003229 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003230 CpyFn, // void (*) (void *, void *) <copy_func>
3231 DidItVal // i32 did_it
3232 };
3233 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3234 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003235}
3236
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003237void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3238 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003239 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003240 if (!CGF.HaveInsertPoint())
3241 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003242 // __kmpc_ordered(ident_t *, gtid);
3243 // OrderedOpGen();
3244 // __kmpc_end_ordered(ident_t *, gtid);
3245 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003246 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003247 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003248 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3249 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3250 Args);
3251 OrderedOpGen.setAction(Action);
3252 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3253 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003254 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003255 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003256}
3257
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003258unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003259 unsigned Flags;
3260 if (Kind == OMPD_for)
3261 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3262 else if (Kind == OMPD_sections)
3263 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3264 else if (Kind == OMPD_single)
3265 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3266 else if (Kind == OMPD_barrier)
3267 Flags = OMP_IDENT_BARRIER_EXPL;
3268 else
3269 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003270 return Flags;
3271}
3272
3273void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
3274 OpenMPDirectiveKind Kind, bool EmitChecks,
3275 bool ForceSimpleCall) {
3276 if (!CGF.HaveInsertPoint())
3277 return;
3278 // Build call __kmpc_cancel_barrier(loc, thread_id);
3279 // Build call __kmpc_barrier(loc, thread_id);
3280 unsigned Flags = getDefaultFlagsForBarriers(Kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003281 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3282 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003283 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3284 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003285 if (auto *OMPRegionInfo =
3286 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003287 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003288 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003289 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003290 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003291 // if (__kmpc_cancel_barrier()) {
3292 // exit from construct;
3293 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003294 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3295 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3296 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003297 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3298 CGF.EmitBlock(ExitBB);
3299 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003300 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003301 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003302 CGF.EmitBranchThroughCleanup(CancelDestination);
3303 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3304 }
3305 return;
3306 }
3307 }
3308 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003309}
3310
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003311/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003312static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003313 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003314 switch (ScheduleKind) {
3315 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003316 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3317 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003318 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003319 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003320 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003321 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003322 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003323 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3324 case OMPC_SCHEDULE_auto:
3325 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003326 case OMPC_SCHEDULE_unknown:
3327 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003328 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003329 }
3330 llvm_unreachable("Unexpected runtime schedule");
3331}
3332
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003333/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003334static OpenMPSchedType
3335getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3336 // only static is allowed for dist_schedule
3337 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3338}
3339
Alexander Musmanc6388682014-12-15 07:07:06 +00003340bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3341 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003342 OpenMPSchedType Schedule =
3343 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003344 return Schedule == OMP_sch_static;
3345}
3346
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003347bool CGOpenMPRuntime::isStaticNonchunked(
3348 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003349 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003350 return Schedule == OMP_dist_sch_static;
3351}
3352
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003353bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
3354 bool Chunked) const {
3355 OpenMPSchedType Schedule =
3356 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3357 return Schedule == OMP_sch_static_chunked;
3358}
3359
3360bool CGOpenMPRuntime::isStaticChunked(
3361 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3362 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3363 return Schedule == OMP_dist_sch_static_chunked;
3364}
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003365
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003366bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003367 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003368 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003369 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3370 return Schedule != OMP_sch_static;
3371}
3372
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003373static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3374 OpenMPScheduleClauseModifier M1,
3375 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003376 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003377 switch (M1) {
3378 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003379 Modifier = OMP_sch_modifier_monotonic;
3380 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003381 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003382 Modifier = OMP_sch_modifier_nonmonotonic;
3383 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003384 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003385 if (Schedule == OMP_sch_static_chunked)
3386 Schedule = OMP_sch_static_balanced_chunked;
3387 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003388 case OMPC_SCHEDULE_MODIFIER_last:
3389 case OMPC_SCHEDULE_MODIFIER_unknown:
3390 break;
3391 }
3392 switch (M2) {
3393 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003394 Modifier = OMP_sch_modifier_monotonic;
3395 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003396 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003397 Modifier = OMP_sch_modifier_nonmonotonic;
3398 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003399 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003400 if (Schedule == OMP_sch_static_chunked)
3401 Schedule = OMP_sch_static_balanced_chunked;
3402 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003403 case OMPC_SCHEDULE_MODIFIER_last:
3404 case OMPC_SCHEDULE_MODIFIER_unknown:
3405 break;
3406 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003407 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003408}
3409
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003410void CGOpenMPRuntime::emitForDispatchInit(
3411 CodeGenFunction &CGF, SourceLocation Loc,
3412 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3413 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003414 if (!CGF.HaveInsertPoint())
3415 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003416 OpenMPSchedType Schedule = getRuntimeSchedule(
3417 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003418 assert(Ordered ||
3419 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003420 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3421 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003422 // Call __kmpc_dispatch_init(
3423 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3424 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3425 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003426
John McCall7f416cc2015-09-08 08:05:57 +00003427 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003428 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3429 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003430 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003431 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3432 CGF.Builder.getInt32(addMonoNonMonoModifier(
3433 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003434 DispatchValues.LB, // Lower
3435 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003436 CGF.Builder.getIntN(IVSize, 1), // Stride
3437 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003438 };
3439 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3440}
3441
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003442static void emitForStaticInitCall(
3443 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
James Y Knight9871db02019-02-05 16:42:33 +00003444 llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003445 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003446 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003447 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003448 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003449
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003450 assert(!Values.Ordered);
3451 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3452 Schedule == OMP_sch_static_balanced_chunked ||
3453 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3454 Schedule == OMP_dist_sch_static ||
3455 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003456
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003457 // Call __kmpc_for_static_init(
3458 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3459 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3460 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3461 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3462 llvm::Value *Chunk = Values.Chunk;
3463 if (Chunk == nullptr) {
3464 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3465 Schedule == OMP_dist_sch_static) &&
3466 "expected static non-chunked schedule");
3467 // If the Chunk was not specified in the clause - use default value 1.
3468 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3469 } else {
3470 assert((Schedule == OMP_sch_static_chunked ||
3471 Schedule == OMP_sch_static_balanced_chunked ||
3472 Schedule == OMP_ord_static_chunked ||
3473 Schedule == OMP_dist_sch_static_chunked) &&
3474 "expected static chunked schedule");
3475 }
3476 llvm::Value *Args[] = {
3477 UpdateLocation,
3478 ThreadId,
3479 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3480 M2)), // Schedule type
3481 Values.IL.getPointer(), // &isLastIter
3482 Values.LB.getPointer(), // &LB
3483 Values.UB.getPointer(), // &UB
3484 Values.ST.getPointer(), // &Stride
3485 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3486 Chunk // Chunk
3487 };
3488 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003489}
3490
John McCall7f416cc2015-09-08 08:05:57 +00003491void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3492 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003493 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003494 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003495 const StaticRTInput &Values) {
3496 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3497 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3498 assert(isOpenMPWorksharingDirective(DKind) &&
3499 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003500 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003501 isOpenMPLoopDirective(DKind)
3502 ? OMP_IDENT_WORK_LOOP
3503 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003504 llvm::Value *ThreadId = getThreadID(CGF, Loc);
James Y Knight9871db02019-02-05 16:42:33 +00003505 llvm::FunctionCallee StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003506 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003507 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003508 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003509}
John McCall7f416cc2015-09-08 08:05:57 +00003510
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003511void CGOpenMPRuntime::emitDistributeStaticInit(
3512 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003513 OpenMPDistScheduleClauseKind SchedKind,
3514 const CGOpenMPRuntime::StaticRTInput &Values) {
3515 OpenMPSchedType ScheduleNum =
3516 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003517 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003518 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003519 llvm::Value *ThreadId = getThreadID(CGF, Loc);
James Y Knight9871db02019-02-05 16:42:33 +00003520 llvm::FunctionCallee StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003521 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003522 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3523 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003524 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003525}
3526
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003527void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003528 SourceLocation Loc,
3529 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003530 if (!CGF.HaveInsertPoint())
3531 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003532 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003533 llvm::Value *Args[] = {
3534 emitUpdateLocation(CGF, Loc,
3535 isOpenMPDistributeDirective(DKind)
3536 ? OMP_IDENT_WORK_DISTRIBUTE
3537 : isOpenMPLoopDirective(DKind)
3538 ? OMP_IDENT_WORK_LOOP
3539 : OMP_IDENT_WORK_SECTIONS),
3540 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003541 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3542 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003543}
3544
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003545void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3546 SourceLocation Loc,
3547 unsigned IVSize,
3548 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003549 if (!CGF.HaveInsertPoint())
3550 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003551 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003552 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003553 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3554}
3555
Alexander Musman92bdaab2015-03-12 13:37:50 +00003556llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3557 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003558 bool IVSigned, Address IL,
3559 Address LB, Address UB,
3560 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003561 // Call __kmpc_dispatch_next(
3562 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3563 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3564 // kmp_int[32|64] *p_stride);
3565 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003566 emitUpdateLocation(CGF, Loc),
3567 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003568 IL.getPointer(), // &isLastIter
3569 LB.getPointer(), // &Lower
3570 UB.getPointer(), // &Upper
3571 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003572 };
3573 llvm::Value *Call =
3574 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3575 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003576 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003577 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003578}
3579
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003580void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3581 llvm::Value *NumThreads,
3582 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003583 if (!CGF.HaveInsertPoint())
3584 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003585 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3586 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003587 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003588 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003589 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3590 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003591}
3592
Alexey Bataev7f210c62015-06-18 13:40:03 +00003593void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3594 OpenMPProcBindClauseKind ProcBind,
3595 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003596 if (!CGF.HaveInsertPoint())
3597 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003598 // Constants for proc bind value accepted by the runtime.
3599 enum ProcBindTy {
3600 ProcBindFalse = 0,
3601 ProcBindTrue,
3602 ProcBindMaster,
3603 ProcBindClose,
3604 ProcBindSpread,
3605 ProcBindIntel,
3606 ProcBindDefault
3607 } RuntimeProcBind;
3608 switch (ProcBind) {
3609 case OMPC_PROC_BIND_master:
3610 RuntimeProcBind = ProcBindMaster;
3611 break;
3612 case OMPC_PROC_BIND_close:
3613 RuntimeProcBind = ProcBindClose;
3614 break;
3615 case OMPC_PROC_BIND_spread:
3616 RuntimeProcBind = ProcBindSpread;
3617 break;
3618 case OMPC_PROC_BIND_unknown:
3619 llvm_unreachable("Unsupported proc_bind value.");
3620 }
3621 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3622 llvm::Value *Args[] = {
3623 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3624 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3625 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3626}
3627
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003628void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3629 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003630 if (!CGF.HaveInsertPoint())
3631 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003632 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003633 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3634 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003635}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003636
Alexey Bataev62b63b12015-03-10 07:28:44 +00003637namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003638/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003639enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003640 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003641 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003642 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003643 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003644 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003645 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003646 /// Function with call of destructors for private variables.
3647 Data1,
3648 /// Task priority.
3649 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003650 /// (Taskloops only) Lower bound.
3651 KmpTaskTLowerBound,
3652 /// (Taskloops only) Upper bound.
3653 KmpTaskTUpperBound,
3654 /// (Taskloops only) Stride.
3655 KmpTaskTStride,
3656 /// (Taskloops only) Is last iteration flag.
3657 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003658 /// (Taskloops only) Reduction data.
3659 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003660};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003661} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003662
Samuel Antaoee8fb302016-01-06 13:42:12 +00003663bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003664 return OffloadEntriesTargetRegion.empty() &&
3665 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003666}
3667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003668/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003669void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3670 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3671 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003672 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003673 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3674 "only required for the device "
3675 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003676 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003677 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003678 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003679 ++OffloadingEntriesNum;
3680}
3681
3682void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3683 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3684 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003685 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003686 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003687 // If we are emitting code for a target, the entry is already initialized,
3688 // only has to be registered.
3689 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003690 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3691 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3692 DiagnosticsEngine::Error,
3693 "Unable to find target region on line '%0' in the device code.");
3694 CGM.getDiags().Report(DiagID) << LineNum;
3695 return;
3696 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003697 auto &Entry =
3698 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003699 assert(Entry.isValid() && "Entry not initialized!");
3700 Entry.setAddress(Addr);
3701 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003702 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003703 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003704 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003705 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003706 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003707 }
3708}
3709
3710bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003711 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3712 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003713 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3714 if (PerDevice == OffloadEntriesTargetRegion.end())
3715 return false;
3716 auto PerFile = PerDevice->second.find(FileID);
3717 if (PerFile == PerDevice->second.end())
3718 return false;
3719 auto PerParentName = PerFile->second.find(ParentName);
3720 if (PerParentName == PerFile->second.end())
3721 return false;
3722 auto PerLine = PerParentName->second.find(LineNum);
3723 if (PerLine == PerParentName->second.end())
3724 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003725 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003726 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003727 return false;
3728 return true;
3729}
3730
3731void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3732 const OffloadTargetRegionEntryInfoActTy &Action) {
3733 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003734 for (const auto &D : OffloadEntriesTargetRegion)
3735 for (const auto &F : D.second)
3736 for (const auto &P : F.second)
3737 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003738 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003739}
3740
Alexey Bataev03f270c2018-03-30 18:31:07 +00003741void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3742 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3743 OMPTargetGlobalVarEntryKind Flags,
3744 unsigned Order) {
3745 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3746 "only required for the device "
3747 "code generation.");
3748 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3749 ++OffloadingEntriesNum;
3750}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003751
Alexey Bataev03f270c2018-03-30 18:31:07 +00003752void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3753 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3754 CharUnits VarSize,
3755 OMPTargetGlobalVarEntryKind Flags,
3756 llvm::GlobalValue::LinkageTypes Linkage) {
3757 if (CGM.getLangOpts().OpenMPIsDevice) {
3758 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3759 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3760 "Entry not initialized!");
3761 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3762 "Resetting with the new address.");
Alexey Bataev8259cc32019-03-12 20:05:17 +00003763 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName)) {
3764 if (Entry.getVarSize().isZero()) {
3765 Entry.setVarSize(VarSize);
3766 Entry.setLinkage(Linkage);
3767 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003768 return;
Alexey Bataev8259cc32019-03-12 20:05:17 +00003769 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003770 Entry.setVarSize(VarSize);
3771 Entry.setLinkage(Linkage);
Alexey Bataev8259cc32019-03-12 20:05:17 +00003772 Entry.setAddress(Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003773 } else {
Alexey Bataev8259cc32019-03-12 20:05:17 +00003774 if (hasDeviceGlobalVarEntryInfo(VarName)) {
3775 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3776 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3777 "Entry not initialized!");
3778 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3779 "Resetting with the new address.");
3780 if (Entry.getVarSize().isZero()) {
3781 Entry.setVarSize(VarSize);
3782 Entry.setLinkage(Linkage);
3783 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003784 return;
Alexey Bataev8259cc32019-03-12 20:05:17 +00003785 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003786 OffloadEntriesDeviceGlobalVar.try_emplace(
3787 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3788 ++OffloadingEntriesNum;
3789 }
3790}
3791
3792void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3793 actOnDeviceGlobalVarEntriesInfo(
3794 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3795 // Scan all target region entries and perform the provided action.
3796 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3797 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003798}
3799
3800llvm::Function *
3801CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003802 // If we don't have entries or if we are emitting code for the device, we
3803 // don't need to do anything.
3804 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3805 return nullptr;
3806
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003807 llvm::Module &M = CGM.getModule();
3808 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003809
3810 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003811 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003812
3813 // We should be creating an offloading descriptor only if there are devices
3814 // specified.
3815 assert(!Devices.empty() && "No OpenMP offloading devices??");
3816
3817 // Create the external variables that will point to the begin and end of the
3818 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003819 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003820 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003821 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003822 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003823 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003824 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003825 EntriesBeginName);
3826 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3827 auto *HostEntriesEnd =
3828 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3829 llvm::GlobalValue::ExternalLinkage,
3830 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003831
3832 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003833 auto *DeviceImageTy = cast<llvm::StructType>(
3834 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003835 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003836 ConstantArrayBuilder DeviceImagesEntries =
3837 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003838
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003839 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003840 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003841 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003842 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003843 M, CGM.Int8Ty, /*isConstant=*/true,
3844 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003845 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3846 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003847 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003848 M, CGM.Int8Ty, /*isConstant=*/true,
3849 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003850 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003851
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003852 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3853 HostEntriesEnd};
3854 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3855 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003856 }
3857
3858 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003859 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003860 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003861 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3862 CGM.getPointerAlign(),
3863 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003864 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003865
3866 // This is a Zero array to be used in the creation of the constant expressions
3867 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3868 llvm::Constant::getNullValue(CGM.Int32Ty)};
3869
3870 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003871 llvm::Constant *Data[] = {
3872 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3873 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3874 DeviceImages, Index),
3875 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003876 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003877 llvm::GlobalVariable *Desc = createGlobalStruct(
3878 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003879
3880 // Emit code to register or unregister the descriptor at execution
3881 // startup or closing, respectively.
3882
Alexey Bataev03f270c2018-03-30 18:31:07 +00003883 llvm::Function *UnRegFn;
3884 {
3885 FunctionArgList Args;
3886 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3887 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003888
Alexey Bataev03f270c2018-03-30 18:31:07 +00003889 CodeGenFunction CGF(CGM);
3890 // Disable debug info for global (de-)initializer because they are not part
3891 // of some particular construct.
3892 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003893 const auto &FI =
3894 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3895 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003896 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3897 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003898 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3899 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3900 Desc);
3901 CGF.FinishFunction();
3902 }
3903 llvm::Function *RegFn;
3904 {
3905 CodeGenFunction CGF(CGM);
3906 // Disable debug info for global (de-)initializer because they are not part
3907 // of some particular construct.
3908 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003909 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003910 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003911
3912 // Encode offload target triples into the registration function name. It
3913 // will serve as a comdat key for the registration/unregistration code for
3914 // this particular combination of offloading targets.
3915 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3916 RegFnNameParts[0] = "omp_offloading";
3917 RegFnNameParts[1] = "descriptor_reg";
3918 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3919 [](const llvm::Triple &T) -> const std::string& {
3920 return T.getTriple();
3921 });
3922 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3923 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003924 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003925 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3926 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3927 // Create a variable to drive the registration and unregistration of the
3928 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3929 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3930 SourceLocation(), nullptr, C.CharTy,
3931 ImplicitParamDecl::Other);
3932 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3933 CGF.FinishFunction();
3934 }
George Rokos29d0f002017-05-27 03:03:13 +00003935 if (CGM.supportsCOMDAT()) {
3936 // It is sufficient to call registration function only once, so create a
3937 // COMDAT group for registration/unregistration functions and associated
3938 // data. That would reduce startup time and code size. Registration
3939 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003940 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003941 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3942 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3943 RegFn->setComdat(ComdatKey);
3944 UnRegFn->setComdat(ComdatKey);
3945 DeviceImages->setComdat(ComdatKey);
3946 Desc->setComdat(ComdatKey);
3947 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003948 return RegFn;
3949}
3950
Alexey Bataev03f270c2018-03-30 18:31:07 +00003951void CGOpenMPRuntime::createOffloadEntry(
3952 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3953 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003954 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003955 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003956 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003957
3958 // Create constant string with the name.
3959 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3960
Alexey Bataev18fa2322018-05-02 14:20:50 +00003961 std::string StringName = getName({"omp_offloading", "entry_name"});
3962 auto *Str = new llvm::GlobalVariable(
3963 M, StrPtrInit->getType(), /*isConstant=*/true,
3964 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003965 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003966
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003967 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3968 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3969 llvm::ConstantInt::get(CGM.SizeTy, Size),
3970 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3971 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003972 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003973 llvm::GlobalVariable *Entry = createGlobalStruct(
3974 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3975 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003976
3977 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003978 std::string Section = getName({"omp_offloading", "entries"});
3979 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003980}
3981
3982void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3983 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003984 // can easily figure out what to emit. The produced metadata looks like
3985 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003986 //
3987 // !omp_offload.info = !{!1, ...}
3988 //
3989 // Right now we only generate metadata for function that contain target
3990 // regions.
3991
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003992 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003993 if (OffloadEntriesInfoManager.empty())
3994 return;
3995
3996 llvm::Module &M = CGM.getModule();
3997 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003998 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003999 OrderedEntries(OffloadEntriesInfoManager.size());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004000 llvm::SmallVector<StringRef, 16> ParentFunctions(
4001 OffloadEntriesInfoManager.size());
Samuel Antaoee8fb302016-01-06 13:42:12 +00004002
Simon Pilgrim2c518802017-03-30 14:13:19 +00004003 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004004 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004005 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004006 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004007 };
4008
Alexey Bataev03f270c2018-03-30 18:31:07 +00004009 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
4010
4011 // Create the offloading info metadata node.
4012 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004013
4014 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00004015 auto &&TargetRegionMetadataEmitter =
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004016 [&C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt, &GetMDString](
Alexey Bataev03f270c2018-03-30 18:31:07 +00004017 unsigned DeviceID, unsigned FileID, StringRef ParentName,
4018 unsigned Line,
4019 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
4020 // Generate metadata for target regions. Each entry of this metadata
4021 // contains:
4022 // - Entry 0 -> Kind of this type of metadata (0).
4023 // - Entry 1 -> Device ID of the file where the entry was identified.
4024 // - Entry 2 -> File ID of the file where the entry was identified.
4025 // - Entry 3 -> Mangled name of the function where the entry was
4026 // identified.
4027 // - Entry 4 -> Line in the file where the entry was identified.
4028 // - Entry 5 -> Order the entry was created.
4029 // The first element of the metadata node is the kind.
4030 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
4031 GetMDInt(FileID), GetMDString(ParentName),
4032 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00004033
Alexey Bataev03f270c2018-03-30 18:31:07 +00004034 // Save this entry in the right position of the ordered entries array.
4035 OrderedEntries[E.getOrder()] = &E;
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004036 ParentFunctions[E.getOrder()] = ParentName;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004037
Alexey Bataev03f270c2018-03-30 18:31:07 +00004038 // Add metadata to the named metadata node.
4039 MD->addOperand(llvm::MDNode::get(C, Ops));
4040 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00004041
4042 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
4043 TargetRegionMetadataEmitter);
4044
Alexey Bataev03f270c2018-03-30 18:31:07 +00004045 // Create function that emits metadata for each device global variable entry;
4046 auto &&DeviceGlobalVarMetadataEmitter =
4047 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
4048 MD](StringRef MangledName,
4049 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
4050 &E) {
4051 // Generate metadata for global variables. Each entry of this metadata
4052 // contains:
4053 // - Entry 0 -> Kind of this type of metadata (1).
4054 // - Entry 1 -> Mangled name of the variable.
4055 // - Entry 2 -> Declare target kind.
4056 // - Entry 3 -> Order the entry was created.
4057 // The first element of the metadata node is the kind.
4058 llvm::Metadata *Ops[] = {
4059 GetMDInt(E.getKind()), GetMDString(MangledName),
4060 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
4061
4062 // Save this entry in the right position of the ordered entries array.
4063 OrderedEntries[E.getOrder()] = &E;
4064
4065 // Add metadata to the named metadata node.
4066 MD->addOperand(llvm::MDNode::get(C, Ops));
4067 };
4068
4069 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
4070 DeviceGlobalVarMetadataEmitter);
4071
4072 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004073 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004074 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00004075 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
4076 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004077 if (!CE->getID() || !CE->getAddress()) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004078 // Do not blame the entry if the parent funtion is not emitted.
4079 StringRef FnName = ParentFunctions[CE->getOrder()];
4080 if (!CGM.GetGlobalValue(FnName))
4081 continue;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004082 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4083 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00004084 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004085 "address or the ID is invalid.");
4086 CGM.getDiags().Report(DiagID);
4087 continue;
4088 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00004089 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004090 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
4091 } else if (const auto *CE =
4092 dyn_cast<OffloadEntriesInfoManagerTy::
4093 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004094 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
4095 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4096 CE->getFlags());
4097 switch (Flags) {
4098 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
4099 if (!CE->getAddress()) {
4100 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4101 DiagnosticsEngine::Error,
4102 "Offloading entry for declare target variable is incorrect: the "
4103 "address is invalid.");
4104 CGM.getDiags().Report(DiagID);
4105 continue;
4106 }
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00004107 // The vaiable has no definition - no need to add the entry.
4108 if (CE->getVarSize().isZero())
4109 continue;
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004110 break;
4111 }
4112 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
4113 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4114 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4115 "Declaret target link address is set.");
4116 if (CGM.getLangOpts().OpenMPIsDevice)
4117 continue;
4118 if (!CE->getAddress()) {
4119 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4120 DiagnosticsEngine::Error,
4121 "Offloading entry for declare target variable is incorrect: the "
4122 "address is invalid.");
4123 CGM.getDiags().Report(DiagID);
4124 continue;
4125 }
4126 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004127 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004128 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004129 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004130 CE->getLinkage());
4131 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004132 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004133 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004134 }
4135}
4136
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004137/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004138/// metadata.
4139void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4140 // If we are in target mode, load the metadata from the host IR. This code has
4141 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4142
4143 if (!CGM.getLangOpts().OpenMPIsDevice)
4144 return;
4145
4146 if (CGM.getLangOpts().OMPHostIRFile.empty())
4147 return;
4148
4149 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004150 if (auto EC = Buf.getError()) {
4151 CGM.getDiags().Report(diag::err_cannot_open_file)
4152 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004153 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004154 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004155
4156 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004157 auto ME = expectedToErrorOrAndEmitErrors(
4158 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004159
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004160 if (auto EC = ME.getError()) {
4161 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4162 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4163 CGM.getDiags().Report(DiagID)
4164 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004165 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004166 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004167
4168 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4169 if (!MD)
4170 return;
4171
George Burgess IV00f70bd2018-03-01 05:43:23 +00004172 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004173 auto &&GetMDInt = [MN](unsigned Idx) {
4174 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004175 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4176 };
4177
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004178 auto &&GetMDString = [MN](unsigned Idx) {
4179 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004180 return V->getString();
4181 };
4182
Alexey Bataev03f270c2018-03-30 18:31:07 +00004183 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004184 default:
4185 llvm_unreachable("Unexpected metadata!");
4186 break;
4187 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004188 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004189 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004190 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4191 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4192 /*Order=*/GetMDInt(5));
4193 break;
4194 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4195 OffloadingEntryInfoDeviceGlobalVar:
4196 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4197 /*MangledName=*/GetMDString(1),
4198 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4199 /*Flags=*/GetMDInt(2)),
4200 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004201 break;
4202 }
4203 }
4204}
4205
Alexey Bataev62b63b12015-03-10 07:28:44 +00004206void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4207 if (!KmpRoutineEntryPtrTy) {
4208 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004209 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004210 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4211 FunctionProtoType::ExtProtoInfo EPI;
4212 KmpRoutineEntryPtrQTy = C.getPointerType(
4213 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4214 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4215 }
4216}
4217
Samuel Antaoee8fb302016-01-06 13:42:12 +00004218QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004219 // Make sure the type of the entry is already created. This is the type we
4220 // have to create:
4221 // struct __tgt_offload_entry{
4222 // void *addr; // Pointer to the offload entry info.
4223 // // (function or global)
4224 // char *name; // Name of the function or global.
4225 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004226 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4227 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004228 // };
4229 if (TgtOffloadEntryQTy.isNull()) {
4230 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004231 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004232 RD->startDefinition();
4233 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4234 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4235 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004236 addFieldToRecordDecl(
4237 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4238 addFieldToRecordDecl(
4239 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004240 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004241 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004242 TgtOffloadEntryQTy = C.getRecordType(RD);
4243 }
4244 return TgtOffloadEntryQTy;
4245}
4246
4247QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4248 // These are the types we need to build:
4249 // struct __tgt_device_image{
4250 // void *ImageStart; // Pointer to the target code start.
4251 // void *ImageEnd; // Pointer to the target code end.
4252 // // We also add the host entries to the device image, as it may be useful
4253 // // for the target runtime to have access to that information.
4254 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4255 // // the entries.
4256 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4257 // // entries (non inclusive).
4258 // };
4259 if (TgtDeviceImageQTy.isNull()) {
4260 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004261 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004262 RD->startDefinition();
4263 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4264 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4265 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4266 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4267 RD->completeDefinition();
4268 TgtDeviceImageQTy = C.getRecordType(RD);
4269 }
4270 return TgtDeviceImageQTy;
4271}
4272
4273QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4274 // struct __tgt_bin_desc{
4275 // int32_t NumDevices; // Number of devices supported.
4276 // __tgt_device_image *DeviceImages; // Arrays of device images
4277 // // (one per device).
4278 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4279 // // entries.
4280 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4281 // // entries (non inclusive).
4282 // };
4283 if (TgtBinaryDescriptorQTy.isNull()) {
4284 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004285 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004286 RD->startDefinition();
4287 addFieldToRecordDecl(
4288 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4289 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4290 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4291 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4292 RD->completeDefinition();
4293 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4294 }
4295 return TgtBinaryDescriptorQTy;
4296}
4297
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004298namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004299struct PrivateHelpersTy {
4300 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4301 const VarDecl *PrivateElemInit)
4302 : Original(Original), PrivateCopy(PrivateCopy),
4303 PrivateElemInit(PrivateElemInit) {}
4304 const VarDecl *Original;
4305 const VarDecl *PrivateCopy;
4306 const VarDecl *PrivateElemInit;
4307};
4308typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004309} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004310
Alexey Bataev9e034042015-05-05 04:05:12 +00004311static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004312createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004313 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004314 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004315 // Build struct .kmp_privates_t. {
4316 // /* private vars */
4317 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004318 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004319 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004320 for (const auto &Pair : Privates) {
4321 const VarDecl *VD = Pair.second.Original;
4322 QualType Type = VD->getType().getNonReferenceType();
4323 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004324 if (VD->hasAttrs()) {
4325 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4326 E(VD->getAttrs().end());
4327 I != E; ++I)
4328 FD->addAttr(*I);
4329 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004330 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004331 RD->completeDefinition();
4332 return RD;
4333 }
4334 return nullptr;
4335}
4336
Alexey Bataev9e034042015-05-05 04:05:12 +00004337static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004338createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4339 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004340 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004341 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004342 // Build struct kmp_task_t {
4343 // void * shareds;
4344 // kmp_routine_entry_t routine;
4345 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004346 // kmp_cmplrdata_t data1;
4347 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004348 // For taskloops additional fields:
4349 // kmp_uint64 lb;
4350 // kmp_uint64 ub;
4351 // kmp_int64 st;
4352 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004353 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004354 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004355 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004356 UD->startDefinition();
4357 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4358 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4359 UD->completeDefinition();
4360 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004361 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004362 RD->startDefinition();
4363 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4364 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4365 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004366 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4367 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004368 if (isOpenMPTaskLoopDirective(Kind)) {
4369 QualType KmpUInt64Ty =
4370 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4371 QualType KmpInt64Ty =
4372 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4373 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4374 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4375 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4376 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004377 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004378 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004379 RD->completeDefinition();
4380 return RD;
4381}
4382
4383static RecordDecl *
4384createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004385 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004386 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004387 // Build struct kmp_task_t_with_privates {
4388 // kmp_task_t task_data;
4389 // .kmp_privates_t. privates;
4390 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004391 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004392 RD->startDefinition();
4393 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004394 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004395 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004396 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004397 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004398}
4399
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004400/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004401/// argument.
4402/// \code
4403/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004404/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004405/// For taskloops:
4406/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004407/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004408/// return 0;
4409/// }
4410/// \endcode
James Y Knight9871db02019-02-05 16:42:33 +00004411static llvm::Function *
Alexey Bataev62b63b12015-03-10 07:28:44 +00004412emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004413 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4414 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004415 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
James Y Knight9871db02019-02-05 16:42:33 +00004416 QualType SharedsPtrTy, llvm::Function *TaskFunction,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004417 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004418 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004419 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004420 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4421 ImplicitParamDecl::Other);
4422 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4423 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4424 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004425 Args.push_back(&GtidArg);
4426 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004427 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004428 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004429 llvm::FunctionType *TaskEntryTy =
4430 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004431 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4432 auto *TaskEntry = llvm::Function::Create(
4433 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004434 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004435 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004436 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004437 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4438 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004439
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004440 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004441 // tt,
4442 // For taskloops:
4443 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4444 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004445 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004446 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004447 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4448 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4449 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004450 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004451 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004452 LValue Base =
4453 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004454 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004455 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004456 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4457 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004458
4459 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004460 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4461 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004462 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004463 CGF.ConvertTypeForMem(SharedsPtrTy));
4464
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004465 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4466 llvm::Value *PrivatesParam;
4467 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004468 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004469 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004470 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004471 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004472 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004473 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004474
Alexey Bataev7292c292016-04-25 12:22:29 +00004475 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4476 TaskPrivatesMap,
4477 CGF.Builder
4478 .CreatePointerBitCastOrAddrSpaceCast(
4479 TDBase.getAddress(), CGF.VoidPtrTy)
4480 .getPointer()};
4481 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4482 std::end(CommonArgs));
4483 if (isOpenMPTaskLoopDirective(Kind)) {
4484 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004485 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4486 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004487 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004488 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4489 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004490 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004491 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4492 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004493 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004494 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4495 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004496 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004497 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4498 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004499 CallArgs.push_back(LBParam);
4500 CallArgs.push_back(UBParam);
4501 CallArgs.push_back(StParam);
4502 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004503 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004504 }
4505 CallArgs.push_back(SharedsParam);
4506
Alexey Bataev3c595a62017-08-14 15:01:03 +00004507 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4508 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004509 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4510 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004511 CGF.FinishFunction();
4512 return TaskEntry;
4513}
4514
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004515static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4516 SourceLocation Loc,
4517 QualType KmpInt32Ty,
4518 QualType KmpTaskTWithPrivatesPtrQTy,
4519 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004520 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004521 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004522 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4523 ImplicitParamDecl::Other);
4524 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4525 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4526 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004527 Args.push_back(&GtidArg);
4528 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004529 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004530 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004531 llvm::FunctionType *DestructorFnTy =
4532 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004533 std::string Name =
4534 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004535 auto *DestructorFn =
4536 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004537 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004538 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004539 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004540 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004541 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004542 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004543 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004544
Alexey Bataev31300ed2016-02-04 11:27:03 +00004545 LValue Base = CGF.EmitLoadOfPointerLValue(
4546 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4547 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004548 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004549 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4550 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004551 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004552 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004553 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004554 if (QualType::DestructionKind DtorKind =
4555 Field->getType().isDestructedType()) {
4556 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004557 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4558 }
4559 }
4560 CGF.FinishFunction();
4561 return DestructorFn;
4562}
4563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004564/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004565/// firstprivate variables.
4566/// \code
4567/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4568/// **noalias priv1,..., <tyn> **noalias privn) {
4569/// *priv1 = &.privates.priv1;
4570/// ...;
4571/// *privn = &.privates.privn;
4572/// }
4573/// \endcode
4574static llvm::Value *
4575emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004576 ArrayRef<const Expr *> PrivateVars,
4577 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004578 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004579 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004580 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004581 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004582 FunctionArgList Args;
4583 ImplicitParamDecl TaskPrivatesArg(
4584 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004585 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4586 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004587 Args.push_back(&TaskPrivatesArg);
4588 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4589 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004590 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004591 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004592 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4593 C.getPointerType(C.getPointerType(E->getType()))
4594 .withConst()
4595 .withRestrict(),
4596 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004597 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004598 PrivateVarsPos[VD] = Counter;
4599 ++Counter;
4600 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004601 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004602 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004603 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4604 C.getPointerType(C.getPointerType(E->getType()))
4605 .withConst()
4606 .withRestrict(),
4607 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004608 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004609 PrivateVarsPos[VD] = Counter;
4610 ++Counter;
4611 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004612 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004613 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004614 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4615 C.getPointerType(C.getPointerType(E->getType()))
4616 .withConst()
4617 .withRestrict(),
4618 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004619 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004620 PrivateVarsPos[VD] = Counter;
4621 ++Counter;
4622 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004623 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004624 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004625 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004626 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004627 std::string Name =
4628 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004629 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004630 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4631 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004632 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004633 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004634 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004635 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004636 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004637 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004638 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004639 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004640
4641 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004642 LValue Base = CGF.EmitLoadOfPointerLValue(
4643 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4644 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004645 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004646 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004647 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4648 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4649 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4650 LValue RefLVal =
4651 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4652 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004653 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004654 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004655 ++Counter;
4656 }
4657 CGF.FinishFunction();
4658 return TaskPrivatesMap;
4659}
4660
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004661static bool stable_sort_comparator(const PrivateDataTy P1,
4662 const PrivateDataTy P2) {
4663 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004664}
4665
Alexey Bataevf93095a2016-05-05 08:46:22 +00004666/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004667static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004668 const OMPExecutableDirective &D,
4669 Address KmpTaskSharedsPtr, LValue TDBase,
4670 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4671 QualType SharedsTy, QualType SharedsPtrTy,
4672 const OMPTaskDataTy &Data,
4673 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004674 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004675 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4676 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004677 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4678 ? OMPD_taskloop
4679 : OMPD_task;
4680 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4681 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004682 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004683 bool IsTargetTask =
4684 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4685 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4686 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4687 // PointersArray and SizesArray. The original variables for these arrays are
4688 // not captured and we get their addresses explicitly.
4689 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004690 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004691 SrcBase = CGF.MakeAddrLValue(
4692 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4693 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4694 SharedsTy);
4695 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004696 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004697 for (const PrivateDataTy &Pair : Privates) {
4698 const VarDecl *VD = Pair.second.PrivateCopy;
4699 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004700 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4701 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004702 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004703 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4704 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004705 // Check if the variable is the target-based BasePointersArray,
4706 // PointersArray or SizesArray.
4707 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004708 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004709 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004710 if (IsTargetTask && !SharedField) {
4711 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4712 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4713 cast<CapturedDecl>(OriginalVD->getDeclContext())
4714 ->getNumParams() == 0 &&
4715 isa<TranslationUnitDecl>(
4716 cast<CapturedDecl>(OriginalVD->getDeclContext())
4717 ->getDeclContext()) &&
4718 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004719 SharedRefLValue =
4720 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4721 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004722 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4723 SharedRefLValue = CGF.MakeAddrLValue(
4724 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4725 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4726 SharedRefLValue.getTBAAInfo());
4727 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004728 if (Type->isArrayType()) {
4729 // Initialize firstprivate array.
4730 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4731 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004732 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004733 } else {
4734 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004735 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004736 CGF.EmitOMPAggregateAssign(
4737 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4738 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4739 Address SrcElement) {
4740 // Clean up any temporaries needed by the initialization.
4741 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4742 InitScope.addPrivate(
4743 Elem, [SrcElement]() -> Address { return SrcElement; });
4744 (void)InitScope.Privatize();
4745 // Emit initialization for single element.
4746 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4747 CGF, &CapturesInfo);
4748 CGF.EmitAnyExprToMem(Init, DestElement,
4749 Init->getType().getQualifiers(),
4750 /*IsInitializer=*/false);
4751 });
4752 }
4753 } else {
4754 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4755 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4756 return SharedRefLValue.getAddress();
4757 });
4758 (void)InitScope.Privatize();
4759 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4760 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4761 /*capturedByInit=*/false);
4762 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004763 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004764 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004765 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004766 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004767 ++FI;
4768 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004769}
4770
4771/// Check if duplication function is required for taskloops.
4772static bool checkInitIsRequired(CodeGenFunction &CGF,
4773 ArrayRef<PrivateDataTy> Privates) {
4774 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004775 for (const PrivateDataTy &Pair : Privates) {
4776 const VarDecl *VD = Pair.second.PrivateCopy;
4777 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004778 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4779 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004780 if (InitRequired)
4781 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004782 }
4783 return InitRequired;
4784}
4785
4786
4787/// Emit task_dup function (for initialization of
4788/// private/firstprivate/lastprivate vars and last_iter flag)
4789/// \code
4790/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4791/// lastpriv) {
4792/// // setup lastprivate flag
4793/// task_dst->last = lastpriv;
4794/// // could be constructor calls here...
4795/// }
4796/// \endcode
4797static llvm::Value *
4798emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4799 const OMPExecutableDirective &D,
4800 QualType KmpTaskTWithPrivatesPtrQTy,
4801 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4802 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4803 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4804 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004805 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004806 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004807 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4808 KmpTaskTWithPrivatesPtrQTy,
4809 ImplicitParamDecl::Other);
4810 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4811 KmpTaskTWithPrivatesPtrQTy,
4812 ImplicitParamDecl::Other);
4813 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4814 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004815 Args.push_back(&DstArg);
4816 Args.push_back(&SrcArg);
4817 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004818 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004819 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004820 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004821 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4822 auto *TaskDup = llvm::Function::Create(
4823 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004824 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004825 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004826 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004827 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4828 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004829
4830 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4831 CGF.GetAddrOfLocalVar(&DstArg),
4832 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4833 // task_dst->liter = lastpriv;
4834 if (WithLastIter) {
4835 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4836 LValue Base = CGF.EmitLValueForField(
4837 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4838 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4839 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4840 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4841 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4842 }
4843
4844 // Emit initial values for private copies (if any).
4845 assert(!Privates.empty());
4846 Address KmpTaskSharedsPtr = Address::invalid();
4847 if (!Data.FirstprivateVars.empty()) {
4848 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4849 CGF.GetAddrOfLocalVar(&SrcArg),
4850 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4851 LValue Base = CGF.EmitLValueForField(
4852 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4853 KmpTaskSharedsPtr = Address(
4854 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4855 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4856 KmpTaskTShareds)),
4857 Loc),
4858 CGF.getNaturalTypeAlignment(SharedsTy));
4859 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004860 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4861 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004862 CGF.FinishFunction();
4863 return TaskDup;
4864}
4865
Alexey Bataev8a831592016-05-10 10:36:51 +00004866/// Checks if destructor function is required to be generated.
4867/// \return true if cleanups are required, false otherwise.
4868static bool
4869checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4870 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004871 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4872 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4873 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004874 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4875 if (NeedsCleanup)
4876 break;
4877 }
4878 return NeedsCleanup;
4879}
4880
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004881CGOpenMPRuntime::TaskResultTy
4882CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4883 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00004884 llvm::Function *TaskFunction, QualType SharedsTy,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004885 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004886 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004887 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004888 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004889 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004890 for (const Expr *E : Data.PrivateVars) {
4891 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004892 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004893 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004894 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004895 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004896 ++I;
4897 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004898 I = Data.FirstprivateCopies.begin();
4899 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004900 for (const Expr *E : Data.FirstprivateVars) {
4901 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004902 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004903 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004904 PrivateHelpersTy(
4905 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004906 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004907 ++I;
4908 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004909 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004910 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004911 for (const Expr *E : Data.LastprivateVars) {
4912 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004913 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004914 C.getDeclAlign(VD),
4915 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004916 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004917 ++I;
4918 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004919 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004920 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004921 // Build type kmp_routine_entry_t (if not built yet).
4922 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004923 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004924 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4925 if (SavedKmpTaskloopTQTy.isNull()) {
4926 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4927 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4928 }
4929 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004930 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004931 assert((D.getDirectiveKind() == OMPD_task ||
4932 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4933 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4934 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004935 if (SavedKmpTaskTQTy.isNull()) {
4936 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4937 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4938 }
4939 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004940 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004941 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004942 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004943 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004944 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004945 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004946 QualType KmpTaskTWithPrivatesPtrQTy =
4947 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004948 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4949 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4950 KmpTaskTWithPrivatesTy->getPointerTo();
4951 llvm::Value *KmpTaskTWithPrivatesTySize =
4952 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004953 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4954
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004955 // Emit initial values for private copies (if any).
4956 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004957 llvm::Type *TaskPrivatesMapTy =
James Y Knight9871db02019-02-05 16:42:33 +00004958 std::next(TaskFunction->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004959 if (!Privates.empty()) {
4960 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004961 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4962 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4963 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004964 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4965 TaskPrivatesMap, TaskPrivatesMapTy);
4966 } else {
4967 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4968 cast<llvm::PointerType>(TaskPrivatesMapTy));
4969 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004970 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4971 // kmp_task_t *tt);
James Y Knight9871db02019-02-05 16:42:33 +00004972 llvm::Function *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004973 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4974 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4975 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004976
4977 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4978 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4979 // kmp_routine_entry_t *task_entry);
4980 // Task flags. Format is taken from
James Y Knight5d71fc52019-01-29 16:37:27 +00004981 // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h,
Alexey Bataev62b63b12015-03-10 07:28:44 +00004982 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004983 enum {
4984 TiedFlag = 0x1,
4985 FinalFlag = 0x2,
4986 DestructorsFlag = 0x8,
4987 PriorityFlag = 0x20
4988 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004989 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004990 bool NeedsCleanup = false;
4991 if (!Privates.empty()) {
4992 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4993 if (NeedsCleanup)
4994 Flags = Flags | DestructorsFlag;
4995 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004996 if (Data.Priority.getInt())
4997 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004998 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004999 Data.Final.getPointer()
5000 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00005001 CGF.Builder.getInt32(FinalFlag),
5002 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005003 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00005004 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005005 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005006 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
5007 getThreadID(CGF, Loc), TaskFlags,
5008 KmpTaskTWithPrivatesTySize, SharedsSize,
5009 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5010 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005011 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00005012 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005013 llvm::Value *NewTaskNewTaskTTy =
5014 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5015 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005016 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
5017 KmpTaskTWithPrivatesQTy);
5018 LValue TDBase =
5019 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00005020 // Fill the data in the resulting kmp_task_t record.
5021 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00005022 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005023 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00005024 KmpTaskSharedsPtr =
5025 Address(CGF.EmitLoadOfScalar(
5026 CGF.EmitLValueForField(
5027 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
5028 KmpTaskTShareds)),
5029 Loc),
5030 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00005031 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
5032 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00005033 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005034 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005035 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00005036 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005037 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00005038 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
5039 SharedsTy, SharedsPtrTy, Data, Privates,
5040 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005041 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
5042 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
5043 Result.TaskDupFn = emitTaskDupFunction(
5044 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
5045 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
5046 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005047 }
5048 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00005049 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
5050 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00005051 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00005052 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005053 const RecordDecl *KmpCmplrdataUD =
5054 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00005055 if (NeedsCleanup) {
5056 llvm::Value *DestructorFn = emitDestructorsFunction(
5057 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
5058 KmpTaskTWithPrivatesQTy);
5059 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
5060 LValue DestructorsLV = CGF.EmitLValueForField(
5061 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
5062 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5063 DestructorFn, KmpRoutineEntryPtrTy),
5064 DestructorsLV);
5065 }
5066 // Set priority.
5067 if (Data.Priority.getInt()) {
5068 LValue Data2LV = CGF.EmitLValueForField(
5069 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
5070 LValue PriorityLV = CGF.EmitLValueForField(
5071 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
5072 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
5073 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005074 Result.NewTask = NewTask;
5075 Result.TaskEntry = TaskEntry;
5076 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
5077 Result.TDBase = TDBase;
5078 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
5079 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00005080}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005081
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005082void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
5083 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00005084 llvm::Function *TaskFunction,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005085 QualType SharedsTy, Address Shareds,
5086 const Expr *IfCond,
5087 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005088 if (!CGF.HaveInsertPoint())
5089 return;
5090
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005091 TaskResultTy Result =
5092 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5093 llvm::Value *NewTask = Result.NewTask;
James Y Knight9871db02019-02-05 16:42:33 +00005094 llvm::Function *TaskEntry = Result.TaskEntry;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005095 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
5096 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005097 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
5098 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005099 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00005100 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005101 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00005102 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005103 // Dependence kind for RTL.
Sergi Mateo Bellido31df1ad2019-02-04 07:33:19 +00005104 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3, DepMutexInOutSet = 0x4 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005105 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
5106 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005107 QualType FlagsTy =
5108 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005109 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
5110 if (KmpDependInfoTy.isNull()) {
5111 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
5112 KmpDependInfoRD->startDefinition();
5113 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
5114 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
5115 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
5116 KmpDependInfoRD->completeDefinition();
5117 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005118 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005119 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005120 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005121 // Define type kmp_depend_info[<Dependences.size()>];
5122 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005123 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005124 ArrayType::Normal, /*IndexTypeQuals=*/0);
5125 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005126 DependenciesArray =
5127 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005128 for (unsigned I = 0; I < NumDependencies; ++I) {
5129 const Expr *E = Data.Dependences[I].second;
5130 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005131 llvm::Value *Size;
5132 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005133 if (const auto *ASE =
5134 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005135 LValue UpAddrLVal =
5136 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5137 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005138 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005139 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005140 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005141 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5142 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005143 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005144 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005145 }
5146 LValue Base = CGF.MakeAddrLValue(
James Y Knight751fe282019-02-09 22:22:28 +00005147 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005148 KmpDependInfoTy);
5149 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005150 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005151 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005152 CGF.EmitStoreOfScalar(
5153 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5154 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005155 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005156 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005157 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5158 CGF.EmitStoreOfScalar(Size, LenLVal);
5159 // deps[i].flags = <Dependences[i].first>;
5160 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005161 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005162 case OMPC_DEPEND_in:
5163 DepKind = DepIn;
5164 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005165 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005166 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005167 case OMPC_DEPEND_inout:
5168 DepKind = DepInOut;
5169 break;
Sergi Mateo Bellido31df1ad2019-02-04 07:33:19 +00005170 case OMPC_DEPEND_mutexinoutset:
5171 DepKind = DepMutexInOutSet;
5172 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005173 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005174 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005175 case OMPC_DEPEND_unknown:
5176 llvm_unreachable("Unknown task dependence type");
5177 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005178 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005179 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5180 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5181 FlagsLVal);
5182 }
John McCall7f416cc2015-09-08 08:05:57 +00005183 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
James Y Knightf5f1b0e2019-02-08 15:34:12 +00005184 CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0), CGF.VoidPtrTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005185 }
5186
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005187 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005188 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005189 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5190 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5191 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5192 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005193 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5194 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005195 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5196 llvm::Value *DepTaskArgs[7];
5197 if (NumDependencies) {
5198 DepTaskArgs[0] = UpLoc;
5199 DepTaskArgs[1] = ThreadID;
5200 DepTaskArgs[2] = NewTask;
5201 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5202 DepTaskArgs[4] = DependenciesArray.getPointer();
5203 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5204 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5205 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005206 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5207 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005208 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005209 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005210 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005211 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005212 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5213 }
John McCall7f416cc2015-09-08 08:05:57 +00005214 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005215 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005216 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005217 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005218 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005219 TaskArgs);
5220 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005221 // Check if parent region is untied and build return for untied task;
5222 if (auto *Region =
5223 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5224 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005225 };
John McCall7f416cc2015-09-08 08:05:57 +00005226
5227 llvm::Value *DepWaitTaskArgs[6];
5228 if (NumDependencies) {
5229 DepWaitTaskArgs[0] = UpLoc;
5230 DepWaitTaskArgs[1] = ThreadID;
5231 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5232 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5233 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5234 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5235 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005236 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005237 NumDependencies, &DepWaitTaskArgs,
5238 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005239 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005240 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5241 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5242 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5243 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5244 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005245 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005246 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005247 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005248 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005249 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5250 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005251 Action.Enter(CGF);
5252 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005253 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005254 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005255 };
5256
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005257 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5258 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005259 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5260 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005261 RegionCodeGenTy RCG(CodeGen);
5262 CommonActionTy Action(
5263 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5264 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5265 RCG.setAction(Action);
5266 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005267 };
John McCall7f416cc2015-09-08 08:05:57 +00005268
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005269 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005270 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005271 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005272 RegionCodeGenTy ThenRCG(ThenCodeGen);
5273 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005274 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005275}
5276
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005277void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5278 const OMPLoopDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00005279 llvm::Function *TaskFunction,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005280 QualType SharedsTy, Address Shareds,
5281 const Expr *IfCond,
5282 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005283 if (!CGF.HaveInsertPoint())
5284 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005285 TaskResultTy Result =
5286 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005287 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005288 // libcall.
5289 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5290 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5291 // sched, kmp_uint64 grainsize, void *task_dup);
5292 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5293 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5294 llvm::Value *IfVal;
5295 if (IfCond) {
5296 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5297 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005298 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005299 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005300 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005301
5302 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005303 Result.TDBase,
5304 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005305 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005306 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5307 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5308 /*IsInitializer=*/true);
5309 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005310 Result.TDBase,
5311 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005312 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005313 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5314 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5315 /*IsInitializer=*/true);
5316 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005317 Result.TDBase,
5318 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005319 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005320 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5321 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5322 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005323 // Store reductions address.
5324 LValue RedLVal = CGF.EmitLValueForField(
5325 Result.TDBase,
5326 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005327 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005328 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005329 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005330 CGF.EmitNullInitialization(RedLVal.getAddress(),
5331 CGF.getContext().VoidPtrTy);
5332 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005333 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005334 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005335 UpLoc,
5336 ThreadID,
5337 Result.NewTask,
5338 IfVal,
5339 LBLVal.getPointer(),
5340 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005341 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataevac6e4de2018-10-24 19:06:37 +00005342 llvm::ConstantInt::getSigned(
5343 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005344 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005345 CGF.IntTy, Data.Schedule.getPointer()
5346 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005347 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005348 Data.Schedule.getPointer()
5349 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005350 /*isSigned=*/false)
5351 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005352 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5353 Result.TaskDupFn, CGF.VoidPtrTy)
5354 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005355 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5356}
5357
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005358/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005359/// array sections) LHS op = RHS.
5360/// \param Type Type of array.
5361/// \param LHSVar Variable on the left side of the reduction operation
5362/// (references element of array in original variable).
5363/// \param RHSVar Variable on the right side of the reduction operation
5364/// (references element of array in original variable).
5365/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5366/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005367static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005368 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5369 const VarDecl *RHSVar,
5370 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5371 const Expr *, const Expr *)> &RedOpGen,
5372 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5373 const Expr *UpExpr = nullptr) {
5374 // Perform element-by-element initialization.
5375 QualType ElementTy;
5376 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5377 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5378
5379 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005380 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5381 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005382
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005383 llvm::Value *RHSBegin = RHSAddr.getPointer();
5384 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005385 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005386 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005387 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005388 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5389 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5390 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005391 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5392 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5393
5394 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005395 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005396 CGF.EmitBlock(BodyBB);
5397
5398 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5399
5400 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5401 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5402 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5403 Address RHSElementCurrent =
5404 Address(RHSElementPHI,
5405 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5406
5407 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5408 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5409 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5410 Address LHSElementCurrent =
5411 Address(LHSElementPHI,
5412 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5413
5414 // Emit copy.
5415 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005416 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5417 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005418 Scope.Privatize();
5419 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5420 Scope.ForceCleanup();
5421
5422 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005423 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005424 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005425 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005426 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5427 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005428 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005429 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5430 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5431 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5432 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5433
5434 // Done.
5435 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5436}
5437
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005438/// Emit reduction combiner. If the combiner is a simple expression emit it as
5439/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5440/// UDR combiner function.
5441static void emitReductionCombiner(CodeGenFunction &CGF,
5442 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005443 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5444 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5445 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005446 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005447 if (const auto *DRD =
5448 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005449 std::pair<llvm::Function *, llvm::Function *> Reduction =
5450 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5451 RValue Func = RValue::get(Reduction.first);
5452 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5453 CGF.EmitIgnoredExpr(ReductionOp);
5454 return;
5455 }
5456 CGF.EmitIgnoredExpr(ReductionOp);
5457}
5458
James Y Knight9871db02019-02-05 16:42:33 +00005459llvm::Function *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005460 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5461 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5462 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005463 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005464
5465 // void reduction_func(void *LHSArg, void *RHSArg);
5466 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005467 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5468 ImplicitParamDecl::Other);
5469 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5470 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005471 Args.push_back(&LHSArg);
5472 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005473 const auto &CGFI =
5474 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005475 std::string Name = getName({"omp", "reduction", "reduction_func"});
5476 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5477 llvm::GlobalValue::InternalLinkage, Name,
5478 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005479 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005480 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005481 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005482 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005483
5484 // Dst = (void*[n])(LHSArg);
5485 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005486 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5487 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5488 ArgsType), CGF.getPointerAlign());
5489 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5490 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5491 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005492
5493 // ...
5494 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5495 // ...
5496 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005497 auto IPriv = Privates.begin();
5498 unsigned Idx = 0;
5499 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005500 const auto *RHSVar =
5501 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5502 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005503 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005504 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005505 const auto *LHSVar =
5506 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5507 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005508 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005509 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005510 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005511 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005512 // Get array size and emit VLA type.
5513 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00005514 Address Elem = CGF.Builder.CreateConstArrayGEP(LHS, Idx);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005515 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005516 const VariableArrayType *VLA =
5517 CGF.getContext().getAsVariableArrayType(PrivTy);
5518 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005519 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005520 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005521 CGF.EmitVariablyModifiedType(PrivTy);
5522 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005523 }
5524 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005525 IPriv = Privates.begin();
5526 auto ILHS = LHSExprs.begin();
5527 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005528 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005529 if ((*IPriv)->getType()->isArrayType()) {
5530 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005531 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5532 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005533 EmitOMPAggregateReduction(
5534 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5535 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5536 emitReductionCombiner(CGF, E);
5537 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005538 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005539 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005540 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005541 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005542 ++IPriv;
5543 ++ILHS;
5544 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005545 }
5546 Scope.ForceCleanup();
5547 CGF.FinishFunction();
5548 return Fn;
5549}
5550
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005551void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5552 const Expr *ReductionOp,
5553 const Expr *PrivateRef,
5554 const DeclRefExpr *LHS,
5555 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005556 if (PrivateRef->getType()->isArrayType()) {
5557 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005558 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5559 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005560 EmitOMPAggregateReduction(
5561 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5562 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5563 emitReductionCombiner(CGF, ReductionOp);
5564 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005565 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005566 // Emit reduction for array subscript or single variable.
5567 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005568 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005569}
5570
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005571void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005572 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005573 ArrayRef<const Expr *> LHSExprs,
5574 ArrayRef<const Expr *> RHSExprs,
5575 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005576 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005577 if (!CGF.HaveInsertPoint())
5578 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005579
5580 bool WithNowait = Options.WithNowait;
5581 bool SimpleReduction = Options.SimpleReduction;
5582
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005583 // Next code should be emitted for reduction:
5584 //
5585 // static kmp_critical_name lock = { 0 };
5586 //
5587 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5588 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5589 // ...
5590 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5591 // *(Type<n>-1*)rhs[<n>-1]);
5592 // }
5593 //
5594 // ...
5595 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5596 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5597 // RedList, reduce_func, &<lock>)) {
5598 // case 1:
5599 // ...
5600 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5601 // ...
5602 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5603 // break;
5604 // case 2:
5605 // ...
5606 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5607 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005608 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005609 // break;
5610 // default:;
5611 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005612 //
5613 // if SimpleReduction is true, only the next code is generated:
5614 // ...
5615 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5616 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005617
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005618 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005619
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005620 if (SimpleReduction) {
5621 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005622 auto IPriv = Privates.begin();
5623 auto ILHS = LHSExprs.begin();
5624 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005625 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005626 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5627 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005628 ++IPriv;
5629 ++ILHS;
5630 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005631 }
5632 return;
5633 }
5634
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005635 // 1. Build a list of reduction variables.
5636 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005637 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005638 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005639 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005640 // Reserve place for array size.
5641 ++Size;
5642 }
5643 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005644 QualType ReductionArrayTy =
5645 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5646 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005647 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005648 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005649 auto IPriv = Privates.begin();
5650 unsigned Idx = 0;
5651 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
James Y Knight751fe282019-02-09 22:22:28 +00005652 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
John McCall7f416cc2015-09-08 08:05:57 +00005653 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005654 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005655 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5656 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005657 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005658 // Store array size.
5659 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00005660 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005661 llvm::Value *Size = CGF.Builder.CreateIntCast(
5662 CGF.getVLASize(
5663 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005664 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005665 CGF.SizeTy, /*isSigned=*/false);
5666 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5667 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005668 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005669 }
5670
5671 // 2. Emit reduce_func().
James Y Knight9871db02019-02-05 16:42:33 +00005672 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005673 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5674 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005675
5676 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005677 std::string Name = getName({"reduction"});
5678 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005679
5680 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5681 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005682 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5683 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5684 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5685 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005686 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005687 llvm::Value *Args[] = {
5688 IdentTLoc, // ident_t *<loc>
5689 ThreadId, // i32 <gtid>
5690 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5691 ReductionArrayTySize, // size_type sizeof(RedList)
5692 RL, // void *RedList
5693 ReductionFn, // void (*) (void *, void *) <reduce_func>
5694 Lock // kmp_critical_name *&<lock>
5695 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005696 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005697 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5698 : OMPRTL__kmpc_reduce),
5699 Args);
5700
5701 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005702 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5703 llvm::SwitchInst *SwInst =
5704 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005705
5706 // 6. Build case 1:
5707 // ...
5708 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5709 // ...
5710 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5711 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005712 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005713 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5714 CGF.EmitBlock(Case1BB);
5715
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005716 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5717 llvm::Value *EndArgs[] = {
5718 IdentTLoc, // ident_t *<loc>
5719 ThreadId, // i32 <gtid>
5720 Lock // kmp_critical_name *&<lock>
5721 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005722 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5723 CodeGenFunction &CGF, PrePostActionTy &Action) {
5724 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005725 auto IPriv = Privates.begin();
5726 auto ILHS = LHSExprs.begin();
5727 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005728 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005729 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5730 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005731 ++IPriv;
5732 ++ILHS;
5733 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005734 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005735 };
5736 RegionCodeGenTy RCG(CodeGen);
5737 CommonActionTy Action(
5738 nullptr, llvm::None,
5739 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5740 : OMPRTL__kmpc_end_reduce),
5741 EndArgs);
5742 RCG.setAction(Action);
5743 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005744
5745 CGF.EmitBranch(DefaultBB);
5746
5747 // 7. Build case 2:
5748 // ...
5749 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5750 // ...
5751 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005752 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005753 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5754 CGF.EmitBlock(Case2BB);
5755
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005756 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5757 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005758 auto ILHS = LHSExprs.begin();
5759 auto IRHS = RHSExprs.begin();
5760 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005761 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005762 const Expr *XExpr = nullptr;
5763 const Expr *EExpr = nullptr;
5764 const Expr *UpExpr = nullptr;
5765 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005766 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005767 if (BO->getOpcode() == BO_Assign) {
5768 XExpr = BO->getLHS();
5769 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005770 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005771 }
5772 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005773 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005774 if (RHSExpr) {
5775 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005776 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005777 RHSExpr->IgnoreParenImpCasts())) {
5778 // If this is a conditional operator, analyze its condition for
5779 // min/max reduction operator.
5780 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005781 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005782 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005783 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5784 EExpr = BORHS->getRHS();
5785 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005786 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005787 }
5788 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005789 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005790 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005791 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5792 const Expr *EExpr, const Expr *UpExpr) {
5793 LValue X = CGF.EmitLValue(XExpr);
5794 RValue E;
5795 if (EExpr)
5796 E = CGF.EmitAnyExpr(EExpr);
5797 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005798 X, E, BO, /*IsXLHSInRHSPart=*/true,
5799 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005800 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005801 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5802 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005803 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005804 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5805 CGF.emitOMPSimpleStore(
5806 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5807 VD->getType().getNonReferenceType(), Loc);
5808 return LHSTemp;
5809 });
5810 (void)PrivateScope.Privatize();
5811 return CGF.EmitAnyExpr(UpExpr);
5812 });
5813 };
5814 if ((*IPriv)->getType()->isArrayType()) {
5815 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005816 const auto *RHSVar =
5817 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005818 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5819 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005820 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005821 // Emit atomic reduction for array subscript or single variable.
5822 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005823 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005824 } else {
5825 // Emit as a critical region.
5826 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005827 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005828 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005829 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005830 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005831 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005832 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5833 Action.Enter(CGF);
5834 emitReductionCombiner(CGF, E);
5835 },
5836 Loc);
5837 };
5838 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005839 const auto *LHSVar =
5840 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5841 const auto *RHSVar =
5842 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005843 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5844 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005845 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005846 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005847 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005848 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005849 ++ILHS;
5850 ++IRHS;
5851 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005852 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005853 };
5854 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5855 if (!WithNowait) {
5856 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5857 llvm::Value *EndArgs[] = {
5858 IdentTLoc, // ident_t *<loc>
5859 ThreadId, // i32 <gtid>
5860 Lock // kmp_critical_name *&<lock>
5861 };
5862 CommonActionTy Action(nullptr, llvm::None,
5863 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5864 EndArgs);
5865 AtomicRCG.setAction(Action);
5866 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005867 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005868 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005869 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005870
5871 CGF.EmitBranch(DefaultBB);
5872 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5873}
5874
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005875/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005876/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5877static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5878 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005879 SmallString<256> Buffer;
5880 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005881 const clang::DeclRefExpr *DE;
5882 const VarDecl *D = ::getBaseDecl(Ref, DE);
5883 if (!D)
5884 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5885 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005886 std::string Name = CGM.getOpenMPRuntime().getName(
5887 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5888 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005889 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005890 return Out.str();
5891}
5892
5893/// Emits reduction initializer function:
5894/// \code
5895/// void @.red_init(void* %arg) {
5896/// %0 = bitcast void* %arg to <type>*
5897/// store <type> <init>, <type>* %0
5898/// ret void
5899/// }
5900/// \endcode
5901static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5902 SourceLocation Loc,
5903 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005904 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005905 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005906 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5907 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005908 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005909 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005910 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005911 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005912 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005913 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005914 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005915 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005916 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005917 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005918 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005919 Address PrivateAddr = CGF.EmitLoadOfPointer(
5920 CGF.GetAddrOfLocalVar(&Param),
5921 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5922 llvm::Value *Size = nullptr;
5923 // If the size of the reduction item is non-constant, load it from global
5924 // threadprivate variable.
5925 if (RCG.getSizes(N).second) {
5926 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5927 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005928 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005929 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5930 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005931 }
5932 RCG.emitAggregateType(CGF, N, Size);
5933 LValue SharedLVal;
5934 // If initializer uses initializer from declare reduction construct, emit a
5935 // pointer to the address of the original reduction item (reuired by reduction
5936 // initializer)
5937 if (RCG.usesReductionInitializer(N)) {
5938 Address SharedAddr =
5939 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5940 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005941 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005942 SharedAddr = CGF.EmitLoadOfPointer(
5943 SharedAddr,
5944 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005945 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5946 } else {
5947 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5948 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5949 CGM.getContext().VoidPtrTy);
5950 }
5951 // Emit the initializer:
5952 // %0 = bitcast void* %arg to <type>*
5953 // store <type> <init>, <type>* %0
5954 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5955 [](CodeGenFunction &) { return false; });
5956 CGF.FinishFunction();
5957 return Fn;
5958}
5959
5960/// Emits reduction combiner function:
5961/// \code
5962/// void @.red_comb(void* %arg0, void* %arg1) {
5963/// %lhs = bitcast void* %arg0 to <type>*
5964/// %rhs = bitcast void* %arg1 to <type>*
5965/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5966/// store <type> %2, <type>* %lhs
5967/// ret void
5968/// }
5969/// \endcode
5970static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5971 SourceLocation Loc,
5972 ReductionCodeGen &RCG, unsigned N,
5973 const Expr *ReductionOp,
5974 const Expr *LHS, const Expr *RHS,
5975 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005976 ASTContext &C = CGM.getContext();
5977 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5978 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005979 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005980 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5981 C.VoidPtrTy, ImplicitParamDecl::Other);
5982 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5983 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005984 Args.emplace_back(&ParamInOut);
5985 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005986 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005987 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005988 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005989 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005990 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005991 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005992 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005993 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005994 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005995 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005996 llvm::Value *Size = nullptr;
5997 // If the size of the reduction item is non-constant, load it from global
5998 // threadprivate variable.
5999 if (RCG.getSizes(N).second) {
6000 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6001 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006002 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006003 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6004 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006005 }
6006 RCG.emitAggregateType(CGF, N, Size);
6007 // Remap lhs and rhs variables to the addresses of the function arguments.
6008 // %lhs = bitcast void* %arg0 to <type>*
6009 // %rhs = bitcast void* %arg1 to <type>*
6010 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006011 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006012 // Pull out the pointer to the variable.
6013 Address PtrAddr = CGF.EmitLoadOfPointer(
6014 CGF.GetAddrOfLocalVar(&ParamInOut),
6015 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6016 return CGF.Builder.CreateElementBitCast(
6017 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
6018 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006019 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006020 // Pull out the pointer to the variable.
6021 Address PtrAddr = CGF.EmitLoadOfPointer(
6022 CGF.GetAddrOfLocalVar(&ParamIn),
6023 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6024 return CGF.Builder.CreateElementBitCast(
6025 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
6026 });
6027 PrivateScope.Privatize();
6028 // Emit the combiner body:
6029 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
6030 // store <type> %2, <type>* %lhs
6031 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
6032 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
6033 cast<DeclRefExpr>(RHS));
6034 CGF.FinishFunction();
6035 return Fn;
6036}
6037
6038/// Emits reduction finalizer function:
6039/// \code
6040/// void @.red_fini(void* %arg) {
6041/// %0 = bitcast void* %arg to <type>*
6042/// <destroy>(<type>* %0)
6043/// ret void
6044/// }
6045/// \endcode
6046static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
6047 SourceLocation Loc,
6048 ReductionCodeGen &RCG, unsigned N) {
6049 if (!RCG.needCleanups(N))
6050 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006051 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006052 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006053 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
6054 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006055 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006056 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006057 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006058 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00006059 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006060 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006061 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00006062 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00006063 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006064 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006065 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006066 Address PrivateAddr = CGF.EmitLoadOfPointer(
6067 CGF.GetAddrOfLocalVar(&Param),
6068 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6069 llvm::Value *Size = nullptr;
6070 // If the size of the reduction item is non-constant, load it from global
6071 // threadprivate variable.
6072 if (RCG.getSizes(N).second) {
6073 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6074 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006075 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006076 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6077 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006078 }
6079 RCG.emitAggregateType(CGF, N, Size);
6080 // Emit the finalizer body:
6081 // <destroy>(<type>* %0)
6082 RCG.emitCleanups(CGF, N, PrivateAddr);
6083 CGF.FinishFunction();
6084 return Fn;
6085}
6086
6087llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
6088 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
6089 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
6090 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
6091 return nullptr;
6092
6093 // Build typedef struct:
6094 // kmp_task_red_input {
6095 // void *reduce_shar; // shared reduction item
6096 // size_t reduce_size; // size of data item
6097 // void *reduce_init; // data initialization routine
6098 // void *reduce_fini; // data finalization routine
6099 // void *reduce_comb; // data combiner routine
6100 // kmp_task_red_flags_t flags; // flags for additional info from compiler
6101 // } kmp_task_red_input_t;
6102 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006103 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006104 RD->startDefinition();
6105 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6106 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
6107 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6108 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6109 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6110 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6111 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6112 RD->completeDefinition();
6113 QualType RDType = C.getRecordType(RD);
6114 unsigned Size = Data.ReductionVars.size();
6115 llvm::APInt ArraySize(/*numBits=*/64, Size);
6116 QualType ArrayRDType = C.getConstantArrayType(
6117 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6118 // kmp_task_red_input_t .rd_input.[Size];
6119 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6120 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6121 Data.ReductionOps);
6122 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6123 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6124 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6125 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6126 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6127 TaskRedInput.getPointer(), Idxs,
6128 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6129 ".rd_input.gep.");
6130 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6131 // ElemLVal.reduce_shar = &Shareds[Cnt];
6132 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6133 RCG.emitSharedLValue(CGF, Cnt);
6134 llvm::Value *CastedShared =
6135 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6136 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6137 RCG.emitAggregateType(CGF, Cnt);
6138 llvm::Value *SizeValInChars;
6139 llvm::Value *SizeVal;
6140 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6141 // We use delayed creation/initialization for VLAs, array sections and
6142 // custom reduction initializations. It is required because runtime does not
6143 // provide the way to pass the sizes of VLAs/array sections to
6144 // initializer/combiner/finalizer functions and does not pass the pointer to
6145 // original reduction item to the initializer. Instead threadprivate global
6146 // variables are used to store these values and use them in the functions.
6147 bool DelayedCreation = !!SizeVal;
6148 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6149 /*isSigned=*/false);
6150 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6151 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6152 // ElemLVal.reduce_init = init;
6153 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6154 llvm::Value *InitAddr =
6155 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6156 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6157 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6158 // ElemLVal.reduce_fini = fini;
6159 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6160 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6161 llvm::Value *FiniAddr = Fini
6162 ? CGF.EmitCastToVoidPtr(Fini)
6163 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6164 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6165 // ElemLVal.reduce_comb = comb;
6166 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6167 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6168 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6169 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6170 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6171 // ElemLVal.flags = 0;
6172 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6173 if (DelayedCreation) {
6174 CGF.EmitStoreOfScalar(
6175 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6176 FlagsLVal);
6177 } else
6178 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6179 }
6180 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6181 // *data);
6182 llvm::Value *Args[] = {
6183 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6184 /*isSigned=*/true),
6185 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6186 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6187 CGM.VoidPtrTy)};
6188 return CGF.EmitRuntimeCall(
6189 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6190}
6191
6192void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6193 SourceLocation Loc,
6194 ReductionCodeGen &RCG,
6195 unsigned N) {
6196 auto Sizes = RCG.getSizes(N);
6197 // Emit threadprivate global variable if the type is non-constant
6198 // (Sizes.second = nullptr).
6199 if (Sizes.second) {
6200 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6201 /*isSigned=*/false);
6202 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6203 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006204 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006205 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6206 }
6207 // Store address of the original reduction item if custom initializer is used.
6208 if (RCG.usesReductionInitializer(N)) {
6209 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6210 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006211 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006212 CGF.Builder.CreateStore(
6213 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6214 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6215 SharedAddr, /*IsVolatile=*/false);
6216 }
6217}
6218
6219Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6220 SourceLocation Loc,
6221 llvm::Value *ReductionsPtr,
6222 LValue SharedLVal) {
6223 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6224 // *d);
6225 llvm::Value *Args[] = {
6226 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6227 /*isSigned=*/true),
6228 ReductionsPtr,
6229 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6230 CGM.VoidPtrTy)};
6231 return Address(
6232 CGF.EmitRuntimeCall(
6233 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6234 SharedLVal.getAlignment());
6235}
6236
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006237void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6238 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006239 if (!CGF.HaveInsertPoint())
6240 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006241 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6242 // global_tid);
6243 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6244 // Ignore return result until untied tasks are supported.
6245 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006246 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6247 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006248}
6249
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006250void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006251 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006252 const RegionCodeGenTy &CodeGen,
6253 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006254 if (!CGF.HaveInsertPoint())
6255 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006256 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006257 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006258}
6259
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006260namespace {
6261enum RTCancelKind {
6262 CancelNoreq = 0,
6263 CancelParallel = 1,
6264 CancelLoop = 2,
6265 CancelSections = 3,
6266 CancelTaskgroup = 4
6267};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006268} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006269
6270static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6271 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006272 if (CancelRegion == OMPD_parallel)
6273 CancelKind = CancelParallel;
6274 else if (CancelRegion == OMPD_for)
6275 CancelKind = CancelLoop;
6276 else if (CancelRegion == OMPD_sections)
6277 CancelKind = CancelSections;
6278 else {
6279 assert(CancelRegion == OMPD_taskgroup);
6280 CancelKind = CancelTaskgroup;
6281 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006282 return CancelKind;
6283}
6284
6285void CGOpenMPRuntime::emitCancellationPointCall(
6286 CodeGenFunction &CGF, SourceLocation Loc,
6287 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006288 if (!CGF.HaveInsertPoint())
6289 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006290 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6291 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006292 if (auto *OMPRegionInfo =
6293 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006294 // For 'cancellation point taskgroup', the task region info may not have a
6295 // cancel. This may instead happen in another adjacent task.
6296 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006297 llvm::Value *Args[] = {
6298 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6299 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006300 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006301 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006302 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6303 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006304 // exit from construct;
6305 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006306 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6307 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6308 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006309 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6310 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006311 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006312 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006313 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006314 CGF.EmitBranchThroughCleanup(CancelDest);
6315 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6316 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006317 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006318}
6319
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006320void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006321 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006322 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006323 if (!CGF.HaveInsertPoint())
6324 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006325 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6326 // kmp_int32 cncl_kind);
6327 if (auto *OMPRegionInfo =
6328 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006329 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6330 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006331 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006332 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006333 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006334 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6335 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006336 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006337 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006338 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006339 // exit from construct;
6340 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006341 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6342 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6343 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006344 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6345 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006346 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006347 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006348 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6349 CGF.EmitBranchThroughCleanup(CancelDest);
6350 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6351 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006352 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006353 emitOMPIfClause(CGF, IfCond, ThenGen,
6354 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006355 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006356 RegionCodeGenTy ThenRCG(ThenGen);
6357 ThenRCG(CGF);
6358 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006359 }
6360}
Samuel Antaobed3c462015-10-02 16:14:20 +00006361
Samuel Antaoee8fb302016-01-06 13:42:12 +00006362void CGOpenMPRuntime::emitTargetOutlinedFunction(
6363 const OMPExecutableDirective &D, StringRef ParentName,
6364 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006365 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006366 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006367 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6368 IsOffloadEntry, CodeGen);
6369}
6370
6371void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6372 const OMPExecutableDirective &D, StringRef ParentName,
6373 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6374 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006375 // Create a unique name for the entry function using the source location
6376 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006377 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006378 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006379 //
6380 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006381 // mangled name of the function that encloses the target region and BB is the
6382 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006383
6384 unsigned DeviceID;
6385 unsigned FileID;
6386 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006387 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006388 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006389 SmallString<64> EntryFnName;
6390 {
6391 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006392 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6393 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006394 }
6395
Alexey Bataev475a7442018-01-12 19:39:11 +00006396 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006397
Samuel Antaobed3c462015-10-02 16:14:20 +00006398 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006399 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006400 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006401
Samuel Antao6d004262016-06-16 18:39:34 +00006402 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006403
6404 // If this target outline function is not an offload entry, we don't need to
6405 // register it.
6406 if (!IsOffloadEntry)
6407 return;
6408
6409 // The target region ID is used by the runtime library to identify the current
6410 // target region, so it only has to be unique and not necessarily point to
6411 // anything. It could be the pointer to the outlined function that implements
6412 // the target region, but we aren't using that so that the compiler doesn't
6413 // need to keep that, and could therefore inline the host function if proven
6414 // worthwhile during optimization. In the other hand, if emitting code for the
6415 // device, the ID has to be the function address so that it can retrieved from
6416 // the offloading entry and launched by the runtime library. We also mark the
6417 // outlined function to have external linkage in case we are emitting code for
6418 // the device, because these functions will be entry points to the device.
6419
6420 if (CGM.getLangOpts().OpenMPIsDevice) {
6421 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006422 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006423 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006424 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006425 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006426 OutlinedFnID = new llvm::GlobalVariable(
6427 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006428 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006429 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006430 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006431
6432 // Register the information for the entry associated with this target region.
6433 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006434 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006435 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006436}
6437
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006438/// discard all CompoundStmts intervening between two constructs
6439static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006440 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006441 Body = CS->body_front();
6442
6443 return Body;
6444}
6445
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006446/// Emit the number of teams for a target directive. Inspect the num_teams
6447/// clause associated with a teams construct combined or closely nested
6448/// with the target directive.
6449///
6450/// Emit a team of size one for directives such as 'target parallel' that
6451/// have no associated teams construct.
6452///
6453/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006454static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006455emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6456 CodeGenFunction &CGF,
6457 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006458 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6459 "teams directive expected to be "
6460 "emitted only for the host!");
6461
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006462 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006463
6464 // If the target directive is combined with a teams directive:
6465 // Return the value in the num_teams clause, if any.
6466 // Otherwise, return 0 to denote the runtime default.
6467 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6468 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6469 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006470 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6471 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006472 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6473 /*IsSigned=*/true);
6474 }
6475
6476 // The default value is 0.
6477 return Bld.getInt32(0);
6478 }
6479
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006480 // If the target directive is combined with a parallel directive but not a
6481 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006482 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6483 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006484
6485 // If the current target region has a teams region enclosed, we need to get
6486 // the number of teams to pass to the runtime function call. This is done
6487 // by generating the expression in a inlined region. This is required because
6488 // the expression is captured in the enclosing target environment when the
6489 // teams directive is not combined with target.
6490
Alexey Bataev475a7442018-01-12 19:39:11 +00006491 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006492
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006493 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006494 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006495 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006496 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006497 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6498 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6499 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6500 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6501 /*IsSigned=*/true);
6502 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006503
Alexey Bataev50a1c782017-12-01 21:31:08 +00006504 // If we have an enclosed teams directive but no num_teams clause we use
6505 // the default value 0.
6506 return Bld.getInt32(0);
6507 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006508 }
6509
6510 // No teams associated with the directive.
6511 return nullptr;
6512}
6513
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006514/// Emit the number of threads for a target directive. Inspect the
6515/// thread_limit clause associated with a teams construct combined or closely
6516/// nested with the target directive.
6517///
6518/// Emit the num_threads clause for directives such as 'target parallel' that
6519/// have no associated teams construct.
6520///
6521/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006522static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006523emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6524 CodeGenFunction &CGF,
6525 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006526 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6527 "teams directive expected to be "
6528 "emitted only for the host!");
6529
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006530 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006531
6532 //
6533 // If the target directive is combined with a teams directive:
6534 // Return the value in the thread_limit clause, if any.
6535 //
6536 // If the target directive is combined with a parallel directive:
6537 // Return the value in the num_threads clause, if any.
6538 //
6539 // If both clauses are set, select the minimum of the two.
6540 //
6541 // If neither teams or parallel combined directives set the number of threads
6542 // in a team, return 0 to denote the runtime default.
6543 //
6544 // If this is not a teams directive return nullptr.
6545
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006546 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6547 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006548 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6549 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006550 llvm::Value *ThreadLimitVal = nullptr;
6551
6552 if (const auto *ThreadLimitClause =
6553 D.getSingleClause<OMPThreadLimitClause>()) {
6554 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006555 llvm::Value *ThreadLimit =
6556 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6557 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006558 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6559 /*IsSigned=*/true);
6560 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006561
6562 if (const auto *NumThreadsClause =
6563 D.getSingleClause<OMPNumThreadsClause>()) {
6564 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6565 llvm::Value *NumThreads =
6566 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6567 /*IgnoreResultAssign*/ true);
6568 NumThreadsVal =
6569 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6570 }
6571
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006572 // Select the lesser of thread_limit and num_threads.
6573 if (NumThreadsVal)
6574 ThreadLimitVal = ThreadLimitVal
6575 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6576 ThreadLimitVal),
6577 NumThreadsVal, ThreadLimitVal)
6578 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006579
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006580 // Set default value passed to the runtime if either teams or a target
6581 // parallel type directive is found but no clause is specified.
6582 if (!ThreadLimitVal)
6583 ThreadLimitVal = DefaultThreadLimitVal;
6584
6585 return ThreadLimitVal;
6586 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006587
Samuel Antaob68e2db2016-03-03 16:20:23 +00006588 // If the current target region has a teams region enclosed, we need to get
6589 // the thread limit to pass to the runtime function call. This is done
6590 // by generating the expression in a inlined region. This is required because
6591 // the expression is captured in the enclosing target environment when the
6592 // teams directive is not combined with target.
6593
Alexey Bataev475a7442018-01-12 19:39:11 +00006594 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006595
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006596 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006597 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006598 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006599 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006600 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6601 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6602 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6603 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6604 /*IsSigned=*/true);
6605 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006606
Alexey Bataev50a1c782017-12-01 21:31:08 +00006607 // If we have an enclosed teams directive but no thread_limit clause we
6608 // use the default value 0.
6609 return CGF.Builder.getInt32(0);
6610 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006611 }
6612
6613 // No teams associated with the directive.
6614 return nullptr;
6615}
6616
Samuel Antao86ace552016-04-27 22:40:57 +00006617namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006618LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6619
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006620// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006621// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6622// It provides a convenient interface to obtain the information and generate
6623// code for that information.
6624class MappableExprsHandler {
6625public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006626 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006627 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006628 enum OpenMPOffloadMappingFlags : uint64_t {
6629 /// No flags
6630 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006631 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006632 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006633 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006634 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006635 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006636 /// if it was already mapped before.
6637 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006638 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006639 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006640 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006641 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006642 /// pointer and the pointee should be mapped.
6643 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006644 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006645 /// passed to the target kernel as an argument.
6646 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006647 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006648 /// in the current position for the data being mapped. Used when we have the
6649 /// use_device_ptr clause.
6650 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006651 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006652 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006653 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006654 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006655 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006656 /// Implicit map
6657 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006658 /// The 16 MSBs of the flags indicate whether the entry is member of some
6659 /// struct/class.
6660 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6661 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006662 };
6663
Samuel Antaocc10b852016-07-28 14:23:26 +00006664 /// Class that associates information with a base pointer to be passed to the
6665 /// runtime library.
6666 class BasePointerInfo {
6667 /// The base pointer.
6668 llvm::Value *Ptr = nullptr;
6669 /// The base declaration that refers to this device pointer, or null if
6670 /// there is none.
6671 const ValueDecl *DevPtrDecl = nullptr;
6672
6673 public:
6674 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6675 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6676 llvm::Value *operator*() const { return Ptr; }
6677 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6678 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6679 };
6680
Alexey Bataevb3638132018-07-19 16:34:13 +00006681 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6682 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6683 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6684
6685 /// Map between a struct and the its lowest & highest elements which have been
6686 /// mapped.
6687 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6688 /// HE(FieldIndex, Pointer)}
6689 struct StructRangeInfoTy {
6690 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6691 0, Address::invalid()};
6692 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6693 0, Address::invalid()};
6694 Address Base = Address::invalid();
6695 };
Samuel Antao86ace552016-04-27 22:40:57 +00006696
6697private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006698 /// Kind that defines how a device pointer has to be returned.
6699 struct MapInfo {
6700 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6701 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
Kelvin Lief579432018-12-18 22:18:41 +00006702 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataevb3638132018-07-19 16:34:13 +00006703 bool ReturnDevicePointer = false;
6704 bool IsImplicit = false;
6705
6706 MapInfo() = default;
6707 MapInfo(
6708 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Kelvin Lief579432018-12-18 22:18:41 +00006709 OpenMPMapClauseKind MapType,
6710 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00006711 bool ReturnDevicePointer, bool IsImplicit)
Kelvin Lief579432018-12-18 22:18:41 +00006712 : Components(Components), MapType(MapType), MapModifiers(MapModifiers),
Alexey Bataevb3638132018-07-19 16:34:13 +00006713 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6714 };
6715
6716 /// If use_device_ptr is used on a pointer which is a struct member and there
6717 /// is no map information about it, then emission of that entry is deferred
6718 /// until the whole struct has been processed.
6719 struct DeferredDevicePtrEntryTy {
6720 const Expr *IE = nullptr;
6721 const ValueDecl *VD = nullptr;
6722
6723 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6724 : IE(IE), VD(VD) {}
6725 };
6726
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006727 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006728 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006729
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006730 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006731 CodeGenFunction &CGF;
6732
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006733 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006734 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6735
Samuel Antao6890b092016-07-28 14:25:09 +00006736 /// Map between device pointer declarations and their expression components.
6737 /// The key value for declarations in 'this' is null.
6738 llvm::DenseMap<
6739 const ValueDecl *,
6740 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6741 DevPointersMap;
6742
Samuel Antao86ace552016-04-27 22:40:57 +00006743 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006744 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006745
6746 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006747 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006748 ExprTy = RefTy->getPointeeType().getCanonicalType();
6749
6750 // Given that an array section is considered a built-in type, we need to
6751 // do the calculation based on the length of the section instead of relying
6752 // on CGF.getTypeSize(E->getType()).
6753 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6754 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6755 OAE->getBase()->IgnoreParenImpCasts())
6756 .getCanonicalType();
6757
6758 // If there is no length associated with the expression, that means we
6759 // are using the whole length of the base.
6760 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6761 return CGF.getTypeSize(BaseTy);
6762
6763 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006764 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006765 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006766 } else {
6767 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006768 assert(ATy && "Expecting array type if not a pointer type.");
6769 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6770 }
6771
6772 // If we don't have a length at this point, that is because we have an
6773 // array section with a single element.
6774 if (!OAE->getLength())
6775 return ElemSize;
6776
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006777 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006778 LengthVal =
6779 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6780 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6781 }
6782 return CGF.getTypeSize(ExprTy);
6783 }
6784
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006785 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006786 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006787 /// map as the first one of a series of maps that relate to the same map
6788 /// expression.
Kelvin Lief579432018-12-18 22:18:41 +00006789 OpenMPOffloadMappingFlags getMapTypeBits(
6790 OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
6791 bool IsImplicit, bool AddPtrFlag, bool AddIsTargetParamFlag) const {
Alexey Bataevb3638132018-07-19 16:34:13 +00006792 OpenMPOffloadMappingFlags Bits =
6793 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006794 switch (MapType) {
6795 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006796 case OMPC_MAP_release:
6797 // alloc and release is the default behavior in the runtime library, i.e.
6798 // if we don't pass any bits alloc/release that is what the runtime is
6799 // going to do. Therefore, we don't need to signal anything for these two
6800 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006801 break;
6802 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006803 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006804 break;
6805 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006806 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006807 break;
6808 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006809 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006810 break;
6811 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006812 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006813 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006814 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006815 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006816 }
6817 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006818 Bits |= OMP_MAP_PTR_AND_OBJ;
6819 if (AddIsTargetParamFlag)
6820 Bits |= OMP_MAP_TARGET_PARAM;
Kelvin Lief579432018-12-18 22:18:41 +00006821 if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_always)
6822 != MapModifiers.end())
Samuel Antao86ace552016-04-27 22:40:57 +00006823 Bits |= OMP_MAP_ALWAYS;
6824 return Bits;
6825 }
6826
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006827 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006828 /// final array section, is one whose length can't be proved to be one.
6829 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006830 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006831
6832 // It is not an array section and therefore not a unity-size one.
6833 if (!OASE)
6834 return false;
6835
6836 // An array section with no colon always refer to a single element.
6837 if (OASE->getColonLoc().isInvalid())
6838 return false;
6839
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006840 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006841
6842 // If we don't have a length we have to check if the array has size 1
6843 // for this dimension. Also, we should always expect a length if the
6844 // base type is pointer.
6845 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006846 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6847 OASE->getBase()->IgnoreParenImpCasts())
6848 .getCanonicalType();
6849 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006850 return ATy->getSize().getSExtValue() != 1;
6851 // If we don't have a constant dimension length, we have to consider
6852 // the current section as having any size, so it is not necessarily
6853 // unitary. If it happen to be unity size, that's user fault.
6854 return true;
6855 }
6856
6857 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +00006858 Expr::EvalResult Result;
6859 if (!Length->EvaluateAsInt(Result, CGF.getContext()))
Samuel Antao86ace552016-04-27 22:40:57 +00006860 return true; // Can have more that size 1.
6861
Fangrui Song407659a2018-11-30 23:41:18 +00006862 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antao86ace552016-04-27 22:40:57 +00006863 return ConstLength.getSExtValue() != 1;
6864 }
6865
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006866 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006867 /// bits for the provided map type, map modifier, and expression components.
6868 /// \a IsFirstComponent should be set to true if the provided set of
6869 /// components is the first associated with a capture.
6870 void generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00006871 OpenMPMapClauseKind MapType,
6872 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Samuel Antao86ace552016-04-27 22:40:57 +00006873 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006874 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006875 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006876 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006877 bool IsImplicit,
6878 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6879 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006880 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006881 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006882 // base pointer, section pointer, size, flags
6883 // (to add to the ones that come from the map type and modifier).
6884 //
6885 // double d;
6886 // int i[100];
6887 // float *p;
6888 //
6889 // struct S1 {
6890 // int i;
6891 // float f[50];
6892 // }
6893 // struct S2 {
6894 // int i;
6895 // float f[50];
6896 // S1 s;
6897 // double *p;
6898 // struct S2 *ps;
6899 // }
6900 // S2 s;
6901 // S2 *ps;
6902 //
6903 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006904 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006905 //
6906 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006907 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006908 //
6909 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006910 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006911 //
6912 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006913 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006914 //
6915 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006916 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006917 //
6918 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006919 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006920 //
6921 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006922 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006923 //
6924 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006925 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006926 //
6927 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006928 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006929 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006930 // map(to: s.p[:22])
6931 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6932 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6933 // &(s.p), &(s.p[0]), 22*sizeof(double),
6934 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6935 // (*) alloc space for struct members, only this is a target parameter
6936 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6937 // optimizes this entry out, same in the examples below)
6938 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006939 //
6940 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006941 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006942 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006943 // map(from: s.ps->s.i)
6944 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6945 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6946 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006947 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006948 // map(to: s.ps->ps)
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 | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006952 //
6953 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006954 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6955 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6956 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6957 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006958 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006959 // map(to: s.ps->ps->s.f[:22])
6960 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6961 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6962 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6963 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006964 //
6965 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006966 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006967 //
6968 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006969 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006970 //
6971 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006972 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006973 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006974 // map(from: ps->p)
6975 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006976 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006977 // map(to: ps->p[:22])
6978 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6979 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6980 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006981 //
6982 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006983 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006984 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006985 // map(from: ps->ps->s.i)
6986 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6987 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6988 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006989 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006990 // map(from: ps->ps->ps)
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 | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006994 //
6995 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006996 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6997 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6998 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6999 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00007000 //
Alexey Bataevb3638132018-07-19 16:34:13 +00007001 // map(to: ps->ps->ps->s.f[:22])
7002 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
7003 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
7004 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
7005 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
7006 //
7007 // map(to: s.f[:22]) map(from: s.p[:33])
7008 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
7009 // sizeof(double*) (**), TARGET_PARAM
7010 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
7011 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
7012 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
7013 // (*) allocate contiguous space needed to fit all mapped members even if
7014 // we allocate space for members not mapped (in this example,
7015 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
7016 // them as well because they fall between &s.f[0] and &s.p)
7017 //
7018 // map(from: s.f[:22]) map(to: ps->p[:33])
7019 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
7020 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7021 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
7022 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
7023 // (*) the struct this entry pertains to is the 2nd element in the list of
7024 // arguments, hence MEMBER_OF(2)
7025 //
7026 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
7027 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
7028 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
7029 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
7030 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7031 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
7032 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
7033 // (*) the struct this entry pertains to is the 4th element in the list
7034 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00007035
7036 // Track if the map information being generated is the first for a capture.
7037 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00007038 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00007039
7040 // Scan the components from the base to the complete expression.
7041 auto CI = Components.rbegin();
7042 auto CE = Components.rend();
7043 auto I = CI;
7044
7045 // Track if the map information being generated is the first for a list of
7046 // components.
7047 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007048 Address BP = Address::invalid();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007049 const Expr *AssocExpr = I->getAssociatedExpression();
7050 const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr);
7051 const auto *OASE = dyn_cast<OMPArraySectionExpr>(AssocExpr);
Samuel Antao86ace552016-04-27 22:40:57 +00007052
Patrick Lystere13b1e32019-01-02 19:28:48 +00007053 if (isa<MemberExpr>(AssocExpr)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007054 // The base is the 'this' pointer. The content of the pointer is going
7055 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00007056 BP = CGF.LoadCXXThisAddress();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007057 } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) ||
7058 (OASE &&
7059 isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) {
7060 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007061 } else {
7062 // The base is the reference to the variable.
7063 // BP = &Var.
Patrick Lystere13b1e32019-01-02 19:28:48 +00007064 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00007065 if (const auto *VD =
7066 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
7067 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007068 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007069 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
7070 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007071 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007072 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007073 }
Samuel Antao86ace552016-04-27 22:40:57 +00007074
7075 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00007076 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00007077 // reference. References are ignored for mapping purposes.
7078 QualType Ty =
7079 I->getAssociatedDeclaration()->getType().getNonReferenceType();
7080 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007081 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00007082
7083 // We do not need to generate individual map information for the
7084 // pointer, it can be associated with the combined storage.
7085 ++I;
7086 }
7087 }
7088
Alexey Bataevb3638132018-07-19 16:34:13 +00007089 // Track whether a component of the list should be marked as MEMBER_OF some
7090 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7091 // in a component list should be marked as MEMBER_OF, all subsequent entries
7092 // do not belong to the base struct. E.g.
7093 // struct S2 s;
7094 // s.ps->ps->ps->f[:]
7095 // (1) (2) (3) (4)
7096 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7097 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7098 // is the pointee of ps(2) which is not member of struct s, so it should not
7099 // be marked as such (it is still PTR_AND_OBJ).
7100 // The variable is initialized to false so that PTR_AND_OBJ entries which
7101 // are not struct members are not considered (e.g. array of pointers to
7102 // data).
7103 bool ShouldBeMemberOf = false;
7104
7105 // Variable keeping track of whether or not we have encountered a component
7106 // in the component list which is a member expression. Useful when we have a
7107 // pointer or a final array section, in which case it is the previous
7108 // component in the list which tells us whether we have a member expression.
7109 // E.g. X.f[:]
7110 // While processing the final array section "[:]" it is "f" which tells us
7111 // whether we are dealing with a member of a declared struct.
7112 const MemberExpr *EncounteredME = nullptr;
7113
Samuel Antao86ace552016-04-27 22:40:57 +00007114 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007115 // If the current component is member of a struct (parent struct) mark it.
7116 if (!EncounteredME) {
7117 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
7118 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
7119 // as MEMBER_OF the parent struct.
7120 if (EncounteredME)
7121 ShouldBeMemberOf = true;
7122 }
7123
Samuel Antao86ace552016-04-27 22:40:57 +00007124 auto Next = std::next(I);
7125
7126 // We need to generate the addresses and sizes if this is the last
7127 // component, if the component is a pointer or if it is an array section
7128 // whose length can't be proved to be one. If this is a pointer, it
7129 // becomes the base address for the following components.
7130
7131 // A final array section, is one whose length can't be proved to be one.
7132 bool IsFinalArraySection =
7133 isFinalArraySectionExpression(I->getAssociatedExpression());
7134
7135 // Get information on whether the element is a pointer. Have to do a
7136 // special treatment for array sections given that they are built-in
7137 // types.
7138 const auto *OASE =
7139 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7140 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007141 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7142 .getCanonicalType()
7143 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007144 I->getAssociatedExpression()->getType()->isAnyPointerType();
7145
7146 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007147 // If this is not the last component, we expect the pointer to be
7148 // associated with an array expression or member expression.
7149 assert((Next == CE ||
7150 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7151 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7152 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7153 "Unexpected expression");
7154
Alexey Bataevb3638132018-07-19 16:34:13 +00007155 Address LB =
7156 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007157
Alexey Bataevb3638132018-07-19 16:34:13 +00007158 // If this component is a pointer inside the base struct then we don't
7159 // need to create any entry for it - it will be combined with the object
7160 // it is pointing to into a single PTR_AND_OBJ entry.
7161 bool IsMemberPointer =
7162 IsPointer && EncounteredME &&
7163 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7164 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007165 if (!OverlappedElements.empty()) {
7166 // Handle base element with the info for overlapped elements.
7167 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7168 assert(Next == CE &&
7169 "Expected last element for the overlapped elements.");
7170 assert(!IsPointer &&
7171 "Unexpected base element with the pointer type.");
7172 // Mark the whole struct as the struct that requires allocation on the
7173 // device.
7174 PartialStruct.LowestElem = {0, LB};
7175 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7176 I->getAssociatedExpression()->getType());
7177 Address HB = CGF.Builder.CreateConstGEP(
7178 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7179 CGF.VoidPtrTy),
James Y Knight751fe282019-02-09 22:22:28 +00007180 TypeSize.getQuantity() - 1);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007181 PartialStruct.HighestElem = {
7182 std::numeric_limits<decltype(
7183 PartialStruct.HighestElem.first)>::max(),
7184 HB};
7185 PartialStruct.Base = BP;
7186 // Emit data for non-overlapped data.
7187 OpenMPOffloadMappingFlags Flags =
7188 OMP_MAP_MEMBER_OF |
Kelvin Lief579432018-12-18 22:18:41 +00007189 getMapTypeBits(MapType, MapModifiers, IsImplicit,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007190 /*AddPtrFlag=*/false,
7191 /*AddIsTargetParamFlag=*/false);
7192 LB = BP;
7193 llvm::Value *Size = nullptr;
7194 // Do bitcopy of all non-overlapped structure elements.
7195 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7196 Component : OverlappedElements) {
7197 Address ComponentLB = Address::invalid();
7198 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7199 Component) {
7200 if (MC.getAssociatedDeclaration()) {
7201 ComponentLB =
7202 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7203 .getAddress();
7204 Size = CGF.Builder.CreatePtrDiff(
7205 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7206 CGF.EmitCastToVoidPtr(LB.getPointer()));
7207 break;
7208 }
7209 }
7210 BasePointers.push_back(BP.getPointer());
7211 Pointers.push_back(LB.getPointer());
7212 Sizes.push_back(Size);
7213 Types.push_back(Flags);
James Y Knight751fe282019-02-09 22:22:28 +00007214 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007215 }
7216 BasePointers.push_back(BP.getPointer());
7217 Pointers.push_back(LB.getPointer());
7218 Size = CGF.Builder.CreatePtrDiff(
7219 CGF.EmitCastToVoidPtr(
James Y Knight751fe282019-02-09 22:22:28 +00007220 CGF.Builder.CreateConstGEP(HB, 1).getPointer()),
Alexey Bataeve82445f2018-09-20 13:54:02 +00007221 CGF.EmitCastToVoidPtr(LB.getPointer()));
7222 Sizes.push_back(Size);
7223 Types.push_back(Flags);
7224 break;
7225 }
7226 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007227 if (!IsMemberPointer) {
7228 BasePointers.push_back(BP.getPointer());
7229 Pointers.push_back(LB.getPointer());
7230 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007231
Alexey Bataevb3638132018-07-19 16:34:13 +00007232 // We need to add a pointer flag for each map that comes from the
7233 // same expression except for the first one. We also need to signal
7234 // this map is the first one that relates with the current capture
7235 // (there is a set of entries for each capture).
7236 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
Kelvin Lief579432018-12-18 22:18:41 +00007237 MapType, MapModifiers, IsImplicit,
Alexey Bataevb3638132018-07-19 16:34:13 +00007238 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7239
7240 if (!IsExpressionFirstInfo) {
7241 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7242 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7243 if (IsPointer)
7244 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7245 OMP_MAP_DELETE);
7246
7247 if (ShouldBeMemberOf) {
7248 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7249 // should be later updated with the correct value of MEMBER_OF.
7250 Flags |= OMP_MAP_MEMBER_OF;
7251 // From now on, all subsequent PTR_AND_OBJ entries should not be
7252 // marked as MEMBER_OF.
7253 ShouldBeMemberOf = false;
7254 }
7255 }
7256
7257 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007258 }
7259
Alexey Bataevb3638132018-07-19 16:34:13 +00007260 // If we have encountered a member expression so far, keep track of the
7261 // mapped member. If the parent is "*this", then the value declaration
7262 // is nullptr.
7263 if (EncounteredME) {
7264 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7265 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007266
Alexey Bataevb3638132018-07-19 16:34:13 +00007267 // Update info about the lowest and highest elements for this struct
7268 if (!PartialStruct.Base.isValid()) {
7269 PartialStruct.LowestElem = {FieldIndex, LB};
7270 PartialStruct.HighestElem = {FieldIndex, LB};
7271 PartialStruct.Base = BP;
7272 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7273 PartialStruct.LowestElem = {FieldIndex, LB};
7274 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7275 PartialStruct.HighestElem = {FieldIndex, LB};
7276 }
7277 }
Samuel Antao86ace552016-04-27 22:40:57 +00007278
7279 // If we have a final array section, we are done with this expression.
7280 if (IsFinalArraySection)
7281 break;
7282
7283 // The pointer becomes the base for the next element.
7284 if (Next != CE)
7285 BP = LB;
7286
7287 IsExpressionFirstInfo = false;
7288 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007289 }
7290 }
7291 }
7292
Alexey Bataevb3638132018-07-19 16:34:13 +00007293 /// Return the adjusted map modifiers if the declaration a capture refers to
7294 /// appears in a first-private clause. This is expected to be used only with
7295 /// directives that start with 'target'.
7296 MappableExprsHandler::OpenMPOffloadMappingFlags
7297 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7298 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7299
7300 // A first private variable captured by reference will use only the
7301 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7302 // declaration is known as first-private in this handler.
Alexey Bataev1af5bd52019-03-05 17:47:18 +00007303 if (FirstPrivateDecls.count(Cap.getCapturedVar())) {
7304 if (Cap.getCapturedVar()->getType().isConstant(CGF.getContext()) &&
7305 Cap.getCaptureKind() == CapturedStmt::VCK_ByRef)
7306 return MappableExprsHandler::OMP_MAP_ALWAYS |
7307 MappableExprsHandler::OMP_MAP_TO;
Alexey Bataevb3638132018-07-19 16:34:13 +00007308 return MappableExprsHandler::OMP_MAP_PRIVATE |
7309 MappableExprsHandler::OMP_MAP_TO;
Alexey Bataev1af5bd52019-03-05 17:47:18 +00007310 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007311 return MappableExprsHandler::OMP_MAP_TO |
7312 MappableExprsHandler::OMP_MAP_FROM;
7313 }
7314
7315 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7316 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7317 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7318 << 48);
7319 }
7320
7321 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7322 OpenMPOffloadMappingFlags MemberOfFlag) {
7323 // If the entry is PTR_AND_OBJ but has not been marked with the special
7324 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7325 // marked as MEMBER_OF.
7326 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7327 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7328 return;
7329
7330 // Reset the placeholder value to prepare the flag for the assignment of the
7331 // proper MEMBER_OF value.
7332 Flags &= ~OMP_MAP_MEMBER_OF;
7333 Flags |= MemberOfFlag;
7334 }
7335
Alexey Bataeve82445f2018-09-20 13:54:02 +00007336 void getPlainLayout(const CXXRecordDecl *RD,
7337 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7338 bool AsBase) const {
7339 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7340
7341 llvm::StructType *St =
7342 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7343
7344 unsigned NumElements = St->getNumElements();
7345 llvm::SmallVector<
7346 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7347 RecordLayout(NumElements);
7348
7349 // Fill bases.
7350 for (const auto &I : RD->bases()) {
7351 if (I.isVirtual())
7352 continue;
7353 const auto *Base = I.getType()->getAsCXXRecordDecl();
7354 // Ignore empty bases.
7355 if (Base->isEmpty() || CGF.getContext()
7356 .getASTRecordLayout(Base)
7357 .getNonVirtualSize()
7358 .isZero())
7359 continue;
7360
7361 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7362 RecordLayout[FieldIndex] = Base;
7363 }
7364 // Fill in virtual bases.
7365 for (const auto &I : RD->vbases()) {
7366 const auto *Base = I.getType()->getAsCXXRecordDecl();
7367 // Ignore empty bases.
7368 if (Base->isEmpty())
7369 continue;
7370 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7371 if (RecordLayout[FieldIndex])
7372 continue;
7373 RecordLayout[FieldIndex] = Base;
7374 }
7375 // Fill in all the fields.
7376 assert(!RD->isUnion() && "Unexpected union.");
7377 for (const auto *Field : RD->fields()) {
7378 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7379 // will fill in later.)
7380 if (!Field->isBitField()) {
7381 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7382 RecordLayout[FieldIndex] = Field;
7383 }
7384 }
7385 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7386 &Data : RecordLayout) {
7387 if (Data.isNull())
7388 continue;
7389 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7390 getPlainLayout(Base, Layout, /*AsBase=*/true);
7391 else
7392 Layout.push_back(Data.get<const FieldDecl *>());
7393 }
7394 }
7395
Alexey Bataevb3638132018-07-19 16:34:13 +00007396public:
7397 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7398 : CurDir(Dir), CGF(CGF) {
7399 // Extract firstprivate clause information.
7400 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7401 for (const auto *D : C->varlists())
7402 FirstPrivateDecls.insert(
7403 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7404 // Extract device pointer clause information.
7405 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7406 for (auto L : C->component_lists())
7407 DevPointersMap[L.first].push_back(L.second);
7408 }
7409
7410 /// Generate code for the combined entry if we have a partially mapped struct
7411 /// and take care of the mapping flags of the arguments corresponding to
7412 /// individual struct members.
7413 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7414 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7415 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7416 const StructRangeInfoTy &PartialStruct) const {
7417 // Base is the base of the struct
7418 BasePointers.push_back(PartialStruct.Base.getPointer());
7419 // Pointer is the address of the lowest element
7420 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7421 Pointers.push_back(LB);
7422 // Size is (addr of {highest+1} element) - (addr of lowest element)
7423 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7424 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7425 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7426 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7427 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7428 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7429 /*isSinged=*/false);
7430 Sizes.push_back(Size);
7431 // Map type is always TARGET_PARAM
7432 Types.push_back(OMP_MAP_TARGET_PARAM);
7433 // Remove TARGET_PARAM flag from the first element
7434 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7435
7436 // All other current entries will be MEMBER_OF the combined entry
7437 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7438 // 0xFFFF in the MEMBER_OF field).
7439 OpenMPOffloadMappingFlags MemberOfFlag =
7440 getMemberOfFlag(BasePointers.size() - 1);
7441 for (auto &M : CurTypes)
7442 setCorrectMemberOfFlag(M, MemberOfFlag);
7443 }
7444
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007445 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007446 /// types for the extracted mappable expressions. Also, for each item that
7447 /// relates with a device pointer, a pair of the relevant declaration and
7448 /// index where it occurs is appended to the device pointers info array.
7449 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007450 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7451 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007452 // We have to process the component lists that relate with the same
7453 // declaration in a single chunk so that we can generate the map flags
7454 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007455 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007456
7457 // Helper function to fill the information map for the different supported
7458 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007459 auto &&InfoGen = [&Info](
7460 const ValueDecl *D,
7461 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
Kelvin Lief579432018-12-18 22:18:41 +00007462 OpenMPMapClauseKind MapType,
7463 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007464 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007465 const ValueDecl *VD =
7466 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Kelvin Lief579432018-12-18 22:18:41 +00007467 Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007468 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007469 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007470
Paul Robinson78fb1322016-08-01 22:12:46 +00007471 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007472 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7473 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007474 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifiers(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007475 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007476 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007477 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7478 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007479 InfoGen(L.first, L.second, OMPC_MAP_to, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007480 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007481 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007482 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7483 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007484 InfoGen(L.first, L.second, OMPC_MAP_from, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007485 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007486 }
Samuel Antao86ace552016-04-27 22:40:57 +00007487
Samuel Antaocc10b852016-07-28 14:23:26 +00007488 // Look at the use_device_ptr clause information and mark the existing map
7489 // entries as such. If there is no map information for an entry in the
7490 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007491 // section. It is the user fault if that was not mapped before. If there is
7492 // no map information and the pointer is a struct member, then we defer the
7493 // emission of that entry until the whole struct has been processed.
7494 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7495 DeferredInfo;
7496
Paul Robinson78fb1322016-08-01 22:12:46 +00007497 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007498 for (const auto *C :
7499 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007500 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007501 assert(!L.second.empty() && "Not expecting empty list of components!");
7502 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7503 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007504 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007505 // If the first component is a member expression, we have to look into
7506 // 'this', which maps to null in the map of map information. Otherwise
7507 // look directly for the information.
7508 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7509
7510 // We potentially have map information for this declaration already.
7511 // Look for the first set of components that refer to it.
7512 if (It != Info.end()) {
7513 auto CI = std::find_if(
7514 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7515 return MI.Components.back().getAssociatedDeclaration() == VD;
7516 });
7517 // If we found a map entry, signal that the pointer has to be returned
7518 // and move on to the next declaration.
7519 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007520 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007521 continue;
7522 }
7523 }
7524
7525 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007526 // size array section - if the pointer is a struct member we defer this
7527 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007528 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007529 if (isa<MemberExpr>(IE)) {
7530 // Insert the pointer into Info to be processed by
7531 // generateInfoForComponentList. Because it is a member pointer
7532 // without a pointee, no entry will be generated for it, therefore
7533 // we need to generate one after the whole struct has been processed.
7534 // Nonetheless, generateInfoForComponentList must be called to take
7535 // the pointer into account for the calculation of the range of the
7536 // partial struct.
Kelvin Lief579432018-12-18 22:18:41 +00007537 InfoGen(nullptr, L.second, OMPC_MAP_unknown, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007538 /*ReturnDevicePointer=*/false, C->isImplicit());
7539 DeferredInfo[nullptr].emplace_back(IE, VD);
7540 } else {
7541 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7542 this->CGF.EmitLValue(IE), IE->getExprLoc());
7543 BasePointers.emplace_back(Ptr, VD);
7544 Pointers.push_back(Ptr);
7545 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7546 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7547 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007548 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007549 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007550
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007551 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007552 // We need to know when we generate information for the first component
7553 // associated with a capture, because the mapping flags depend on it.
7554 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007555
7556 // Temporary versions of arrays
7557 MapBaseValuesArrayTy CurBasePointers;
7558 MapValuesArrayTy CurPointers;
7559 MapValuesArrayTy CurSizes;
7560 MapFlagsArrayTy CurTypes;
7561 StructRangeInfoTy PartialStruct;
7562
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007563 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007564 assert(!L.Components.empty() &&
7565 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007566
7567 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007568 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007569 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007570 this->generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007571 L.MapType, L.MapModifiers, L.Components, CurBasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007572 CurPointers, CurSizes, CurTypes, PartialStruct,
7573 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007574
7575 // If this entry relates with a device pointer, set the relevant
7576 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007577 if (L.ReturnDevicePointer) {
7578 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007579 "Unexpected number of mapped base pointers.");
7580
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007581 const ValueDecl *RelevantVD =
7582 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007583 assert(RelevantVD &&
7584 "No relevant declaration related with device pointer??");
7585
Alexey Bataevb3638132018-07-19 16:34:13 +00007586 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7587 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007588 }
Samuel Antao86ace552016-04-27 22:40:57 +00007589 IsFirstComponentList = false;
7590 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007591
7592 // Append any pending zero-length pointers which are struct members and
7593 // used with use_device_ptr.
7594 auto CI = DeferredInfo.find(M.first);
7595 if (CI != DeferredInfo.end()) {
7596 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7597 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7598 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7599 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7600 CurBasePointers.emplace_back(BasePtr, L.VD);
7601 CurPointers.push_back(Ptr);
7602 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7603 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7604 // value MEMBER_OF=FFFF so that the entry is later updated with the
7605 // correct value of MEMBER_OF.
7606 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7607 OMP_MAP_MEMBER_OF);
7608 }
7609 }
7610
7611 // If there is an entry in PartialStruct it means we have a struct with
7612 // individual members mapped. Emit an extra combined entry.
7613 if (PartialStruct.Base.isValid())
7614 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7615 PartialStruct);
7616
7617 // We need to append the results of this capture to what we already have.
7618 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7619 Pointers.append(CurPointers.begin(), CurPointers.end());
7620 Sizes.append(CurSizes.begin(), CurSizes.end());
7621 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007622 }
7623 }
7624
Alexey Bataev60705422018-10-30 15:50:12 +00007625 /// Emit capture info for lambdas for variables captured by reference.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007626 void generateInfoForLambdaCaptures(
7627 const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
7628 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7629 MapFlagsArrayTy &Types,
7630 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007631 const auto *RD = VD->getType()
7632 .getCanonicalType()
7633 .getNonReferenceType()
7634 ->getAsCXXRecordDecl();
7635 if (!RD || !RD->isLambda())
7636 return;
7637 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
7638 LValue VDLVal = CGF.MakeAddrLValue(
7639 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
7640 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
7641 FieldDecl *ThisCapture = nullptr;
7642 RD->getCaptureFields(Captures, ThisCapture);
7643 if (ThisCapture) {
7644 LValue ThisLVal =
7645 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007646 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
7647 LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
7648 BasePointers.push_back(ThisLVal.getPointer());
7649 Pointers.push_back(ThisLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007650 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007651 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007652 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7653 }
7654 for (const LambdaCapture &LC : RD->captures()) {
7655 if (LC.getCaptureKind() != LCK_ByRef)
7656 continue;
7657 const VarDecl *VD = LC.getCapturedVar();
7658 auto It = Captures.find(VD);
7659 assert(It != Captures.end() && "Found lambda capture without field.");
7660 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007661 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
7662 LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
7663 BasePointers.push_back(VarLVal.getPointer());
7664 Pointers.push_back(VarLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007665 Sizes.push_back(CGF.getTypeSize(
7666 VD->getType().getCanonicalType().getNonReferenceType()));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007667 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007668 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7669 }
7670 }
7671
7672 /// Set correct indices for lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007673 void adjustMemberOfForLambdaCaptures(
7674 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
7675 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
7676 MapFlagsArrayTy &Types) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007677 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
7678 // Set correct member_of idx for all implicit lambda captures.
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007679 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007680 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
7681 continue;
Alexey Bataev969dbc02018-11-08 15:47:39 +00007682 llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
7683 assert(BasePtr && "Unable to find base lambda address.");
Alexey Bataev60705422018-10-30 15:50:12 +00007684 int TgtIdx = -1;
7685 for (unsigned J = I; J > 0; --J) {
7686 unsigned Idx = J - 1;
7687 if (Pointers[Idx] != BasePtr)
7688 continue;
7689 TgtIdx = Idx;
7690 break;
7691 }
7692 assert(TgtIdx != -1 && "Unable to find parent lambda.");
7693 // All other current entries will be MEMBER_OF the combined entry
7694 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7695 // 0xFFFF in the MEMBER_OF field).
7696 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
7697 setCorrectMemberOfFlag(Types[I], MemberOfFlag);
7698 }
7699 }
7700
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007701 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007702 /// associated to a given capture.
7703 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007704 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007705 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007706 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007707 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7708 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007709 assert(!Cap->capturesVariableArrayType() &&
7710 "Not expecting to generate map info for a variable array type!");
7711
Samuel Antao6890b092016-07-28 14:25:09 +00007712 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007713 const ValueDecl *VD = Cap->capturesThis()
7714 ? nullptr
7715 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007716
Samuel Antao6890b092016-07-28 14:25:09 +00007717 // If this declaration appears in a is_device_ptr clause we just have to
7718 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007719 // pass its value.
7720 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007721 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007722 Pointers.push_back(Arg);
7723 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007724 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007725 return;
7726 }
7727
Alexey Bataeve82445f2018-09-20 13:54:02 +00007728 using MapData =
7729 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
Kelvin Lief579432018-12-18 22:18:41 +00007730 OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>, bool>;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007731 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007732 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007733 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007734 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007735 assert(L.first == VD &&
7736 "We got information for the wrong declaration??");
7737 assert(!L.second.empty() &&
7738 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007739 DeclComponentLists.emplace_back(L.second, C->getMapType(),
Kelvin Lief579432018-12-18 22:18:41 +00007740 C->getMapTypeModifiers(),
Alexey Bataeve82445f2018-09-20 13:54:02 +00007741 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007742 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007743 }
7744
7745 // Find overlapping elements (including the offset from the base element).
7746 llvm::SmallDenseMap<
7747 const MapData *,
7748 llvm::SmallVector<
7749 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7750 4>
7751 OverlappedData;
7752 size_t Count = 0;
7753 for (const MapData &L : DeclComponentLists) {
7754 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7755 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007756 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007757 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007758 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007759 ++Count;
7760 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7761 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
Kelvin Lief579432018-12-18 22:18:41 +00007762 std::tie(Components1, MapType, MapModifiers, IsImplicit) = L1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007763 auto CI = Components.rbegin();
7764 auto CE = Components.rend();
7765 auto SI = Components1.rbegin();
7766 auto SE = Components1.rend();
7767 for (; CI != CE && SI != SE; ++CI, ++SI) {
7768 if (CI->getAssociatedExpression()->getStmtClass() !=
7769 SI->getAssociatedExpression()->getStmtClass())
7770 break;
7771 // Are we dealing with different variables/fields?
7772 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7773 break;
7774 }
7775 // Found overlapping if, at least for one component, reached the head of
7776 // the components list.
7777 if (CI == CE || SI == SE) {
7778 assert((CI != CE || SI != SE) &&
7779 "Unexpected full match of the mapping components.");
7780 const MapData &BaseData = CI == CE ? L : L1;
7781 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7782 SI == SE ? Components : Components1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007783 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7784 OverlappedElements.getSecond().push_back(SubData);
7785 }
7786 }
7787 }
7788 // Sort the overlapped elements for each item.
7789 llvm::SmallVector<const FieldDecl *, 4> Layout;
7790 if (!OverlappedData.empty()) {
7791 if (const auto *CRD =
7792 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7793 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7794 else {
7795 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7796 Layout.append(RD->field_begin(), RD->field_end());
7797 }
7798 }
7799 for (auto &Pair : OverlappedData) {
7800 llvm::sort(
7801 Pair.getSecond(),
7802 [&Layout](
7803 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7804 OMPClauseMappableExprCommon::MappableExprComponentListRef
7805 Second) {
7806 auto CI = First.rbegin();
7807 auto CE = First.rend();
7808 auto SI = Second.rbegin();
7809 auto SE = Second.rend();
7810 for (; CI != CE && SI != SE; ++CI, ++SI) {
7811 if (CI->getAssociatedExpression()->getStmtClass() !=
7812 SI->getAssociatedExpression()->getStmtClass())
7813 break;
7814 // Are we dealing with different variables/fields?
7815 if (CI->getAssociatedDeclaration() !=
7816 SI->getAssociatedDeclaration())
7817 break;
7818 }
Richard Trieu5061e832018-09-21 21:20:33 +00007819
7820 // Lists contain the same elements.
7821 if (CI == CE && SI == SE)
7822 return false;
7823
7824 // List with less elements is less than list with more elements.
7825 if (CI == CE || SI == SE)
7826 return CI == CE;
7827
Alexey Bataeve82445f2018-09-20 13:54:02 +00007828 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7829 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7830 if (FD1->getParent() == FD2->getParent())
7831 return FD1->getFieldIndex() < FD2->getFieldIndex();
7832 const auto It =
7833 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7834 return FD == FD1 || FD == FD2;
7835 });
7836 return *It == FD1;
7837 });
7838 }
7839
7840 // Associated with a capture, because the mapping flags depend on it.
7841 // Go through all of the elements with the overlapped elements.
7842 for (const auto &Pair : OverlappedData) {
7843 const MapData &L = *Pair.getFirst();
7844 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7845 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007846 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007847 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007848 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007849 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7850 OverlappedComponents = Pair.getSecond();
7851 bool IsFirstComponentList = true;
Kelvin Lief579432018-12-18 22:18:41 +00007852 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007853 BasePointers, Pointers, Sizes, Types,
7854 PartialStruct, IsFirstComponentList,
7855 IsImplicit, OverlappedComponents);
7856 }
7857 // Go through other elements without overlapped elements.
7858 bool IsFirstComponentList = OverlappedData.empty();
7859 for (const MapData &L : DeclComponentLists) {
7860 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7861 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007862 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007863 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007864 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007865 auto It = OverlappedData.find(&L);
7866 if (It == OverlappedData.end())
Kelvin Lief579432018-12-18 22:18:41 +00007867 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007868 BasePointers, Pointers, Sizes, Types,
7869 PartialStruct, IsFirstComponentList,
7870 IsImplicit);
7871 IsFirstComponentList = false;
7872 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007873 }
Samuel Antao86ace552016-04-27 22:40:57 +00007874
Alexey Bataevb3638132018-07-19 16:34:13 +00007875 /// Generate the base pointers, section pointers, sizes and map types
7876 /// associated with the declare target link variables.
7877 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7878 MapValuesArrayTy &Pointers,
7879 MapValuesArrayTy &Sizes,
7880 MapFlagsArrayTy &Types) const {
7881 // Map other list items in the map clause which are not captured variables
7882 // but "declare target link" global variables.,
7883 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7884 for (const auto &L : C->component_lists()) {
7885 if (!L.first)
7886 continue;
7887 const auto *VD = dyn_cast<VarDecl>(L.first);
7888 if (!VD)
7889 continue;
7890 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007891 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007892 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7893 continue;
7894 StructRangeInfoTy PartialStruct;
7895 generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007896 C->getMapType(), C->getMapTypeModifiers(), L.second, BasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007897 Pointers, Sizes, Types, PartialStruct,
7898 /*IsFirstComponentList=*/true, C->isImplicit());
7899 assert(!PartialStruct.Base.isValid() &&
7900 "No partial structs for declare target link expected.");
7901 }
7902 }
Samuel Antao86ace552016-04-27 22:40:57 +00007903 }
Samuel Antaod486f842016-05-26 16:53:38 +00007904
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007905 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007906 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007907 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7908 const FieldDecl &RI, llvm::Value *CV,
7909 MapBaseValuesArrayTy &CurBasePointers,
7910 MapValuesArrayTy &CurPointers,
7911 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007912 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007913 // Do the default mapping.
7914 if (CI.capturesThis()) {
7915 CurBasePointers.push_back(CV);
7916 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007917 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007918 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7919 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007920 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007921 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007922 CurBasePointers.push_back(CV);
7923 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007924 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007925 // We have to signal to the runtime captures passed by value that are
7926 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007927 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007928 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7929 } else {
7930 // Pointers are implicitly mapped with a zero size and no flags
7931 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007932 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007933 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7934 }
7935 } else {
7936 assert(CI.capturesVariable() && "Expected captured reference.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007937 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007938 QualType ElementType = PtrTy->getPointeeType();
7939 CurSizes.push_back(CGF.getTypeSize(ElementType));
7940 // The default map type for a scalar/complex type is 'to' because by
7941 // default the value doesn't have to be retrieved. For an aggregate
7942 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007943 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Alexey Bataev1af5bd52019-03-05 17:47:18 +00007944 const VarDecl *VD = CI.getCapturedVar();
7945 if (FirstPrivateDecls.count(VD) &&
7946 VD->getType().isConstant(CGF.getContext())) {
7947 llvm::Constant *Addr =
7948 CGF.CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(CGF, VD);
7949 // Copy the value of the original variable to the new global copy.
7950 CGF.Builder.CreateMemCpy(
7951 CGF.MakeNaturalAlignAddrLValue(Addr, ElementType).getAddress(),
7952 Address(CV, CGF.getContext().getTypeAlignInChars(ElementType)),
7953 CurSizes.back(),
7954 /*isVolatile=*/false);
7955 // Use new global variable as the base pointers.
7956 CurBasePointers.push_back(Addr);
7957 CurPointers.push_back(Addr);
7958 } else {
7959 CurBasePointers.push_back(CV);
7960 CurPointers.push_back(CV);
7961 }
Samuel Antaod486f842016-05-26 16:53:38 +00007962 }
George Rokos065755d2017-11-07 18:27:04 +00007963 // Every default map produces a single argument which is a target parameter.
7964 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007965
7966 // Add flag stating this is an implicit map.
7967 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007968 }
Samuel Antao86ace552016-04-27 22:40:57 +00007969};
Samuel Antaodf158d52016-04-27 22:58:19 +00007970
7971enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007972 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007973 /// from environment variables in the spec.
7974 OMP_DEVICEID_UNDEF = -1,
7975};
7976} // anonymous namespace
7977
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007978/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007979/// offloading runtime library. If there is no map or capture information,
7980/// return nullptr by reference.
7981static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007982emitOffloadingArrays(CodeGenFunction &CGF,
7983 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007984 MappableExprsHandler::MapValuesArrayTy &Pointers,
7985 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007986 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7987 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007988 CodeGenModule &CGM = CGF.CGM;
7989 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007990
Samuel Antaocc10b852016-07-28 14:23:26 +00007991 // Reset the array information.
7992 Info.clearArrayInfo();
7993 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007994
Samuel Antaocc10b852016-07-28 14:23:26 +00007995 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007996 // Detect if we have any capture size requiring runtime evaluation of the
7997 // size so that a constant array could be eventually used.
7998 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007999 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00008000 if (!isa<llvm::Constant>(S)) {
8001 hasRuntimeEvaluationCaptureSize = true;
8002 break;
8003 }
8004
Samuel Antaocc10b852016-07-28 14:23:26 +00008005 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00008006 QualType PointerArrayType =
8007 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
8008 /*IndexTypeQuals=*/0);
8009
Samuel Antaocc10b852016-07-28 14:23:26 +00008010 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00008011 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00008012 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00008013 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
8014
8015 // If we don't have any VLA types or other types that require runtime
8016 // evaluation, we can use a constant array for the map sizes, otherwise we
8017 // need to fill up the arrays as we do for the pointers.
8018 if (hasRuntimeEvaluationCaptureSize) {
8019 QualType SizeArrayType = Ctx.getConstantArrayType(
8020 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
8021 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00008022 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00008023 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
8024 } else {
8025 // We expect all the sizes to be constant, so we collect them to create
8026 // a constant array.
8027 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008028 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00008029 ConstSizes.push_back(cast<llvm::Constant>(S));
8030
8031 auto *SizesArrayInit = llvm::ConstantArray::get(
8032 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008033 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008034 auto *SizesArrayGbl = new llvm::GlobalVariable(
8035 CGM.getModule(), SizesArrayInit->getType(),
8036 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008037 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008038 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008039 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008040 }
8041
8042 // The map types are always constant so we don't need to generate code to
8043 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00008044 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
8045 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00008046 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00008047 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008048 std::string MaptypesName =
8049 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008050 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
8051 CGM.getModule(), MapTypesArrayInit->getType(),
8052 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008053 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008054 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008055 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008056
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008057 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
8058 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008059 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008060 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008061 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008062 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8063 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008064 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8065 CGF.Builder.CreateStore(BPVal, BPAddr);
8066
Samuel Antaocc10b852016-07-28 14:23:26 +00008067 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008068 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00008069 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00008070
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008071 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008072 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008073 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008074 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008075 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8076 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008077 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8078 CGF.Builder.CreateStore(PVal, PAddr);
8079
8080 if (hasRuntimeEvaluationCaptureSize) {
8081 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008082 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
8083 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008084 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008085 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00008086 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
8087 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008088 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00008089 SAddr);
8090 }
8091 }
8092 }
8093}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008094/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00008095/// arrays of pointers, sizes and map types.
8096static void emitOffloadingArraysArgument(
8097 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
8098 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008099 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008100 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00008101 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008102 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008103 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8104 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008105 /*Idx0=*/0, /*Idx1=*/0);
8106 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008107 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8108 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008109 /*Idx0=*/0,
8110 /*Idx1=*/0);
8111 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008112 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008113 /*Idx0=*/0, /*Idx1=*/0);
8114 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00008115 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00008116 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008117 /*Idx0=*/0,
8118 /*Idx1=*/0);
8119 } else {
8120 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8121 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8122 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
8123 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00008124 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00008125 }
Samuel Antao86ace552016-04-27 22:40:57 +00008126}
8127
Alexey Bataev7bb33532019-01-07 21:30:43 +00008128/// Checks if the expression is constant or does not have non-trivial function
8129/// calls.
8130static bool isTrivial(ASTContext &Ctx, const Expr * E) {
8131 // We can skip constant expressions.
8132 // We can skip expressions with trivial calls or simple expressions.
8133 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
8134 !E->hasNonTrivialCall(Ctx)) &&
8135 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
8136}
8137
8138/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
8139/// iff there is only one that is not evaluatable at the compile time.
8140static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
8141 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
8142 const Stmt *Child = nullptr;
8143 for (const Stmt *S : C->body()) {
8144 if (const auto *E = dyn_cast<Expr>(S)) {
8145 if (isTrivial(Ctx, E))
8146 continue;
8147 }
8148 // Some of the statements can be ignored.
8149 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
8150 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
8151 continue;
8152 // Analyze declarations.
8153 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
8154 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
8155 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
8156 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
8157 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
8158 isa<UsingDirectiveDecl>(D) ||
8159 isa<OMPDeclareReductionDecl>(D) ||
8160 isa<OMPThreadPrivateDecl>(D))
8161 return true;
8162 const auto *VD = dyn_cast<VarDecl>(D);
8163 if (!VD)
8164 return false;
8165 return VD->isConstexpr() ||
8166 ((VD->getType().isTrivialType(Ctx) ||
8167 VD->getType()->isReferenceType()) &&
8168 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
8169 }))
8170 continue;
8171 }
8172 // Found multiple children - cannot get the one child only.
8173 if (Child)
8174 return Body;
8175 Child = S;
8176 }
8177 if (Child)
8178 return Child;
8179 }
8180 return Body;
8181}
8182
8183/// Check for inner distribute directive.
8184static const OMPExecutableDirective *
8185getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) {
8186 const auto *CS = D.getInnermostCapturedStmt();
8187 const auto *Body =
8188 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
8189 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
8190
8191 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8192 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
8193 switch (D.getDirectiveKind()) {
8194 case OMPD_target:
8195 if (isOpenMPDistributeDirective(DKind))
8196 return NestedDir;
8197 if (DKind == OMPD_teams) {
8198 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
8199 /*IgnoreCaptured=*/true);
8200 if (!Body)
8201 return nullptr;
8202 ChildStmt = getSingleCompoundChild(Ctx, Body);
8203 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8204 DKind = NND->getDirectiveKind();
8205 if (isOpenMPDistributeDirective(DKind))
8206 return NND;
8207 }
8208 }
8209 return nullptr;
8210 case OMPD_target_teams:
8211 if (isOpenMPDistributeDirective(DKind))
8212 return NestedDir;
8213 return nullptr;
8214 case OMPD_target_parallel:
8215 case OMPD_target_simd:
8216 case OMPD_target_parallel_for:
8217 case OMPD_target_parallel_for_simd:
8218 return nullptr;
8219 case OMPD_target_teams_distribute:
8220 case OMPD_target_teams_distribute_simd:
8221 case OMPD_target_teams_distribute_parallel_for:
8222 case OMPD_target_teams_distribute_parallel_for_simd:
8223 case OMPD_parallel:
8224 case OMPD_for:
8225 case OMPD_parallel_for:
8226 case OMPD_parallel_sections:
8227 case OMPD_for_simd:
8228 case OMPD_parallel_for_simd:
8229 case OMPD_cancel:
8230 case OMPD_cancellation_point:
8231 case OMPD_ordered:
8232 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008233 case OMPD_allocate:
Alexey Bataev7bb33532019-01-07 21:30:43 +00008234 case OMPD_task:
8235 case OMPD_simd:
8236 case OMPD_sections:
8237 case OMPD_section:
8238 case OMPD_single:
8239 case OMPD_master:
8240 case OMPD_critical:
8241 case OMPD_taskyield:
8242 case OMPD_barrier:
8243 case OMPD_taskwait:
8244 case OMPD_taskgroup:
8245 case OMPD_atomic:
8246 case OMPD_flush:
8247 case OMPD_teams:
8248 case OMPD_target_data:
8249 case OMPD_target_exit_data:
8250 case OMPD_target_enter_data:
8251 case OMPD_distribute:
8252 case OMPD_distribute_simd:
8253 case OMPD_distribute_parallel_for:
8254 case OMPD_distribute_parallel_for_simd:
8255 case OMPD_teams_distribute:
8256 case OMPD_teams_distribute_simd:
8257 case OMPD_teams_distribute_parallel_for:
8258 case OMPD_teams_distribute_parallel_for_simd:
8259 case OMPD_target_update:
8260 case OMPD_declare_simd:
8261 case OMPD_declare_target:
8262 case OMPD_end_declare_target:
8263 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008264 case OMPD_declare_mapper:
Alexey Bataev7bb33532019-01-07 21:30:43 +00008265 case OMPD_taskloop:
8266 case OMPD_taskloop_simd:
8267 case OMPD_requires:
8268 case OMPD_unknown:
8269 llvm_unreachable("Unexpected directive.");
8270 }
8271 }
8272
8273 return nullptr;
8274}
8275
8276void CGOpenMPRuntime::emitTargetNumIterationsCall(
8277 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *Device,
8278 const llvm::function_ref<llvm::Value *(
8279 CodeGenFunction &CGF, const OMPLoopDirective &D)> &SizeEmitter) {
8280 OpenMPDirectiveKind Kind = D.getDirectiveKind();
8281 const OMPExecutableDirective *TD = &D;
8282 // Get nested teams distribute kind directive, if any.
8283 if (!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind))
8284 TD = getNestedDistributeDirective(CGM.getContext(), D);
8285 if (!TD)
8286 return;
8287 const auto *LD = cast<OMPLoopDirective>(TD);
8288 auto &&CodeGen = [LD, &Device, &SizeEmitter, this](CodeGenFunction &CGF,
8289 PrePostActionTy &) {
8290 llvm::Value *NumIterations = SizeEmitter(CGF, *LD);
8291
8292 // Emit device ID if any.
8293 llvm::Value *DeviceID;
8294 if (Device)
8295 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
8296 CGF.Int64Ty, /*isSigned=*/true);
8297 else
8298 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8299
8300 llvm::Value *Args[] = {DeviceID, NumIterations};
8301 CGF.EmitRuntimeCall(
8302 createRuntimeFunction(OMPRTL__kmpc_push_target_tripcount), Args);
8303 };
8304 emitInlinedDirective(CGF, OMPD_unknown, CodeGen);
8305}
8306
Samuel Antaobed3c462015-10-02 16:14:20 +00008307void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
8308 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00008309 llvm::Function *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00008310 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008311 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00008312 if (!CGF.HaveInsertPoint())
8313 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00008314
Samuel Antaoee8fb302016-01-06 13:42:12 +00008315 assert(OutlinedFn && "Invalid outlined function!");
8316
Alexey Bataev8451efa2018-01-15 19:06:12 +00008317 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
8318 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00008319 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008320 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
8321 PrePostActionTy &) {
8322 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8323 };
8324 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00008325
Alexey Bataev8451efa2018-01-15 19:06:12 +00008326 CodeGenFunction::OMPTargetDataInfo InputInfo;
8327 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00008328 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008329 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
8330 &MapTypesArray, &CS, RequiresOuterTask,
8331 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008332 // On top of the arrays that were filled up, the target offloading call
8333 // takes as arguments the device id as well as the host pointer. The host
8334 // pointer is used by the runtime library to identify the current target
8335 // region, so it only has to be unique and not necessarily point to
8336 // anything. It could be the pointer to the outlined function that
8337 // implements the target region, but we aren't using that so that the
8338 // compiler doesn't need to keep that, and could therefore inline the host
8339 // function if proven worthwhile during optimization.
8340
Samuel Antaoee8fb302016-01-06 13:42:12 +00008341 // From this point on, we need to have an ID of the target region defined.
8342 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00008343
8344 // Emit device ID if any.
8345 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00008346 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008347 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008348 CGF.Int64Ty, /*isSigned=*/true);
8349 } else {
8350 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8351 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008352
Samuel Antaodf158d52016-04-27 22:58:19 +00008353 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008354 llvm::Value *PointerNum =
8355 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00008356
Samuel Antaob68e2db2016-03-03 16:20:23 +00008357 // Return value of the runtime offloading call.
8358 llvm::Value *Return;
8359
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008360 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
8361 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008362
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008363 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008364 // The target region is an outlined function launched by the runtime
8365 // via calls __tgt_target() or __tgt_target_teams().
8366 //
8367 // __tgt_target() launches a target region with one team and one thread,
8368 // executing a serial region. This master thread may in turn launch
8369 // more threads within its team upon encountering a parallel region,
8370 // however, no additional teams can be launched on the device.
8371 //
8372 // __tgt_target_teams() launches a target region with one or more teams,
8373 // each with one or more threads. This call is required for target
8374 // constructs such as:
8375 // 'target teams'
8376 // 'target' / 'teams'
8377 // 'target teams distribute parallel for'
8378 // 'target parallel'
8379 // and so on.
8380 //
8381 // Note that on the host and CPU targets, the runtime implementation of
8382 // these calls simply call the outlined function without forking threads.
8383 // The outlined functions themselves have runtime calls to
8384 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
8385 // the compiler in emitTeamsCall() and emitParallelCall().
8386 //
8387 // In contrast, on the NVPTX target, the implementation of
8388 // __tgt_target_teams() launches a GPU kernel with the requested number
8389 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00008390 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008391 // If we have NumTeams defined this means that we have an enclosed teams
8392 // region. Therefore we also expect to have NumThreads defined. These two
8393 // values should be defined in the presence of a teams directive,
8394 // regardless of having any clauses associated. If the user is using teams
8395 // but no clauses, these two values will be the default that should be
8396 // passed to the runtime library - a 32-bit integer with the value zero.
8397 assert(NumThreads && "Thread limit expression should be available along "
8398 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00008399 llvm::Value *OffloadingArgs[] = {DeviceID,
8400 OutlinedFnID,
8401 PointerNum,
8402 InputInfo.BasePointersArray.getPointer(),
8403 InputInfo.PointersArray.getPointer(),
8404 InputInfo.SizesArray.getPointer(),
8405 MapTypesArray,
8406 NumTeams,
8407 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00008408 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008409 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8410 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008411 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008412 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008413 llvm::Value *OffloadingArgs[] = {DeviceID,
8414 OutlinedFnID,
8415 PointerNum,
8416 InputInfo.BasePointersArray.getPointer(),
8417 InputInfo.PointersArray.getPointer(),
8418 InputInfo.SizesArray.getPointer(),
8419 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008420 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008421 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8422 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008423 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008424 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008425
Alexey Bataev2a007e02017-10-02 14:20:58 +00008426 // Check the error code and execute the host version if required.
8427 llvm::BasicBlock *OffloadFailedBlock =
8428 CGF.createBasicBlock("omp_offload.failed");
8429 llvm::BasicBlock *OffloadContBlock =
8430 CGF.createBasicBlock("omp_offload.cont");
8431 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8432 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8433
8434 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008435 if (RequiresOuterTask) {
8436 CapturedVars.clear();
8437 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8438 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008439 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008440 CGF.EmitBranch(OffloadContBlock);
8441
8442 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008443 };
8444
Samuel Antaoee8fb302016-01-06 13:42:12 +00008445 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008446 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8447 RequiresOuterTask](CodeGenFunction &CGF,
8448 PrePostActionTy &) {
8449 if (RequiresOuterTask) {
8450 CapturedVars.clear();
8451 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8452 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008453 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008454 };
8455
8456 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8457 &CapturedVars, RequiresOuterTask,
8458 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8459 // Fill up the arrays with all the captured variables.
8460 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8461 MappableExprsHandler::MapValuesArrayTy Pointers;
8462 MappableExprsHandler::MapValuesArrayTy Sizes;
8463 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8464
Alexey Bataev8451efa2018-01-15 19:06:12 +00008465 // Get mappable expression information.
8466 MappableExprsHandler MEHandler(D, CGF);
Alexey Bataev969dbc02018-11-08 15:47:39 +00008467 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008468
8469 auto RI = CS.getCapturedRecordDecl()->field_begin();
8470 auto CV = CapturedVars.begin();
8471 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8472 CE = CS.capture_end();
8473 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008474 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8475 MappableExprsHandler::MapValuesArrayTy CurPointers;
8476 MappableExprsHandler::MapValuesArrayTy CurSizes;
8477 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8478 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008479
8480 // VLA sizes are passed to the outlined region by copy and do not have map
8481 // information associated.
8482 if (CI->capturesVariableArrayType()) {
8483 CurBasePointers.push_back(*CV);
8484 CurPointers.push_back(*CV);
8485 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8486 // Copy to the device as an argument. No need to retrieve it.
8487 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8488 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8489 } else {
8490 // If we have any information in the map clause, we use it, otherwise we
8491 // just do a default mapping.
8492 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008493 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008494 if (CurBasePointers.empty())
8495 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8496 CurPointers, CurSizes, CurMapTypes);
Alexey Bataev60705422018-10-30 15:50:12 +00008497 // Generate correct mapping for variables captured by reference in
8498 // lambdas.
8499 if (CI->capturesVariable())
Alexey Bataev969dbc02018-11-08 15:47:39 +00008500 MEHandler.generateInfoForLambdaCaptures(
8501 CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
8502 CurMapTypes, LambdaPointers);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008503 }
8504 // We expect to have at least an element of information for this capture.
8505 assert(!CurBasePointers.empty() &&
8506 "Non-existing map pointer for capture!");
8507 assert(CurBasePointers.size() == CurPointers.size() &&
8508 CurBasePointers.size() == CurSizes.size() &&
8509 CurBasePointers.size() == CurMapTypes.size() &&
8510 "Inconsistent map information sizes!");
8511
Alexey Bataevb3638132018-07-19 16:34:13 +00008512 // If there is an entry in PartialStruct it means we have a struct with
8513 // individual members mapped. Emit an extra combined entry.
8514 if (PartialStruct.Base.isValid())
8515 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8516 CurMapTypes, PartialStruct);
8517
Alexey Bataev8451efa2018-01-15 19:06:12 +00008518 // We need to append the results of this capture to what we already have.
8519 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8520 Pointers.append(CurPointers.begin(), CurPointers.end());
8521 Sizes.append(CurSizes.begin(), CurSizes.end());
8522 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8523 }
Alexey Bataev60705422018-10-30 15:50:12 +00008524 // Adjust MEMBER_OF flags for the lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00008525 MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
8526 Pointers, MapTypes);
Alexey Bataev92327c52018-03-26 16:40:55 +00008527 // Map other list items in the map clause which are not captured variables
8528 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008529 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8530 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008531
8532 TargetDataInfo Info;
8533 // Fill up the arrays and create the arguments.
8534 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8535 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8536 Info.PointersArray, Info.SizesArray,
8537 Info.MapTypesArray, Info);
8538 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8539 InputInfo.BasePointersArray =
8540 Address(Info.BasePointersArray, CGM.getPointerAlign());
8541 InputInfo.PointersArray =
8542 Address(Info.PointersArray, CGM.getPointerAlign());
8543 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8544 MapTypesArray = Info.MapTypesArray;
8545 if (RequiresOuterTask)
8546 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8547 else
8548 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8549 };
8550
8551 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8552 CodeGenFunction &CGF, PrePostActionTy &) {
8553 if (RequiresOuterTask) {
8554 CodeGenFunction::OMPTargetDataInfo InputInfo;
8555 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8556 } else {
8557 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8558 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008559 };
8560
8561 // If we have a target function ID it means that we need to support
8562 // offloading, otherwise, just execute on the host. We need to execute on host
8563 // regardless of the conditional in the if clause if, e.g., the user do not
8564 // specify target triples.
8565 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008566 if (IfCond) {
8567 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8568 } else {
8569 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008570 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008571 }
8572 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008573 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008574 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008575 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008576}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008577
8578void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8579 StringRef ParentName) {
8580 if (!S)
8581 return;
8582
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008583 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008584 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008585 isa<OMPExecutableDirective>(S) &&
8586 isOpenMPTargetExecutionDirective(
8587 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008588
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008589 if (RequiresDeviceCodegen) {
8590 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008591 unsigned DeviceID;
8592 unsigned FileID;
8593 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008594 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008595 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008596
8597 // Is this a target region that should not be emitted as an entry point? If
8598 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008599 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8600 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008601 return;
8602
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008603 switch (E.getDirectiveKind()) {
8604 case OMPD_target:
8605 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8606 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008607 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008608 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008609 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008610 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008611 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008612 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008613 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008614 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008615 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008616 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008617 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008618 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008619 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008620 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008621 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008622 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008623 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008624 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008625 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008626 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008627 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008628 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008629 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008630 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008631 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008632 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008633 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008634 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008635 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008636 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008637 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8638 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008639 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008640 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008641 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008642 CodeGenFunction::
8643 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8644 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008645 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008646 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008647 case OMPD_parallel:
8648 case OMPD_for:
8649 case OMPD_parallel_for:
8650 case OMPD_parallel_sections:
8651 case OMPD_for_simd:
8652 case OMPD_parallel_for_simd:
8653 case OMPD_cancel:
8654 case OMPD_cancellation_point:
8655 case OMPD_ordered:
8656 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008657 case OMPD_allocate:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008658 case OMPD_task:
8659 case OMPD_simd:
8660 case OMPD_sections:
8661 case OMPD_section:
8662 case OMPD_single:
8663 case OMPD_master:
8664 case OMPD_critical:
8665 case OMPD_taskyield:
8666 case OMPD_barrier:
8667 case OMPD_taskwait:
8668 case OMPD_taskgroup:
8669 case OMPD_atomic:
8670 case OMPD_flush:
8671 case OMPD_teams:
8672 case OMPD_target_data:
8673 case OMPD_target_exit_data:
8674 case OMPD_target_enter_data:
8675 case OMPD_distribute:
8676 case OMPD_distribute_simd:
8677 case OMPD_distribute_parallel_for:
8678 case OMPD_distribute_parallel_for_simd:
8679 case OMPD_teams_distribute:
8680 case OMPD_teams_distribute_simd:
8681 case OMPD_teams_distribute_parallel_for:
8682 case OMPD_teams_distribute_parallel_for_simd:
8683 case OMPD_target_update:
8684 case OMPD_declare_simd:
8685 case OMPD_declare_target:
8686 case OMPD_end_declare_target:
8687 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008688 case OMPD_declare_mapper:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008689 case OMPD_taskloop:
8690 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008691 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008692 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008693 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8694 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008695 return;
8696 }
8697
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008698 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008699 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008700 return;
8701
8702 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008703 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008704 return;
8705 }
8706
8707 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008708 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008709 S = L->getBody();
8710
8711 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008712 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008713 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008714}
8715
8716bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008717 // If emitting code for the host, we do not process FD here. Instead we do
8718 // the normal code generation.
8719 if (!CGM.getLangOpts().OpenMPIsDevice)
8720 return false;
8721
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008722 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008723 StringRef Name = CGM.getMangledName(GD);
8724 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008725 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008726 scanForTargetRegionsFunctions(FD->getBody(), Name);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008727
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008728 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008729 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008730 AlreadyEmittedTargetFunctions.count(Name) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008731}
8732
8733bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8734 if (!CGM.getLangOpts().OpenMPIsDevice)
8735 return false;
8736
8737 // Check if there are Ctors/Dtors in this declaration and look for target
8738 // regions in it. We use the complete variant to produce the kernel name
8739 // mangling.
8740 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008741 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8742 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008743 StringRef ParentName =
8744 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8745 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8746 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008747 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008748 StringRef ParentName =
8749 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8750 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8751 }
8752 }
8753
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008754 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008755 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008756 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8757 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008758 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008759 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008760 return true;
8761 }
8762 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008763}
8764
Alexey Bataev1af5bd52019-03-05 17:47:18 +00008765llvm::Constant *
8766CGOpenMPRuntime::registerTargetFirstprivateCopy(CodeGenFunction &CGF,
8767 const VarDecl *VD) {
8768 assert(VD->getType().isConstant(CGM.getContext()) &&
8769 "Expected constant variable.");
8770 StringRef VarName;
8771 llvm::Constant *Addr;
8772 llvm::GlobalValue::LinkageTypes Linkage;
8773 QualType Ty = VD->getType();
8774 SmallString<128> Buffer;
8775 {
8776 unsigned DeviceID;
8777 unsigned FileID;
8778 unsigned Line;
8779 getTargetEntryUniqueInfo(CGM.getContext(), VD->getLocation(), DeviceID,
8780 FileID, Line);
8781 llvm::raw_svector_ostream OS(Buffer);
8782 OS << "__omp_offloading_firstprivate_" << llvm::format("_%x", DeviceID)
8783 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
8784 VarName = OS.str();
8785 }
8786 Linkage = llvm::GlobalValue::InternalLinkage;
8787 Addr =
8788 getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(Ty), VarName,
8789 getDefaultFirstprivateAddressSpace());
8790 cast<llvm::GlobalValue>(Addr)->setLinkage(Linkage);
8791 CharUnits VarSize = CGM.getContext().getTypeSizeInChars(Ty);
8792 CGM.addCompilerUsedGlobal(cast<llvm::GlobalValue>(Addr));
8793 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8794 VarName, Addr, VarSize,
8795 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo, Linkage);
8796 return Addr;
8797}
8798
Alexey Bataev03f270c2018-03-30 18:31:07 +00008799void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8800 llvm::Constant *Addr) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008801 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
8802 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
8803 if (!Res) {
8804 if (CGM.getLangOpts().OpenMPIsDevice) {
8805 // Register non-target variables being emitted in device code (debug info
8806 // may cause this).
8807 StringRef VarName = CGM.getMangledName(VD);
8808 EmittedNonTargetVariables.try_emplace(VarName, Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008809 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008810 return;
Alexey Bataev03f270c2018-03-30 18:31:07 +00008811 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008812 // Register declare target variables.
8813 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8814 StringRef VarName;
8815 CharUnits VarSize;
8816 llvm::GlobalValue::LinkageTypes Linkage;
8817 switch (*Res) {
8818 case OMPDeclareTargetDeclAttr::MT_To:
8819 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8820 VarName = CGM.getMangledName(VD);
8821 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8822 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8823 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8824 } else {
8825 VarSize = CharUnits::Zero();
8826 }
8827 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
8828 // Temp solution to prevent optimizations of the internal variables.
8829 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8830 std::string RefName = getName({VarName, "ref"});
8831 if (!CGM.GetGlobalValue(RefName)) {
8832 llvm::Constant *AddrRef =
8833 getOrCreateInternalVariable(Addr->getType(), RefName);
8834 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8835 GVAddrRef->setConstant(/*Val=*/true);
8836 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8837 GVAddrRef->setInitializer(Addr);
8838 CGM.addCompilerUsedGlobal(GVAddrRef);
8839 }
8840 }
8841 break;
8842 case OMPDeclareTargetDeclAttr::MT_Link:
8843 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8844 if (CGM.getLangOpts().OpenMPIsDevice) {
8845 VarName = Addr->getName();
8846 Addr = nullptr;
8847 } else {
8848 VarName = getAddrOfDeclareTargetLink(VD).getName();
8849 Addr = cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8850 }
8851 VarSize = CGM.getPointerSize();
8852 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8853 break;
8854 }
8855 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8856 VarName, Addr, VarSize, Flags, Linkage);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008857}
8858
Samuel Antaoee8fb302016-01-06 13:42:12 +00008859bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008860 if (isa<FunctionDecl>(GD.getDecl()) ||
8861 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008862 return emitTargetFunctions(GD);
8863
8864 return emitTargetGlobalVariable(GD);
8865}
8866
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008867void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8868 for (const VarDecl *VD : DeferredGlobalVariables) {
8869 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008870 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008871 if (!Res)
8872 continue;
8873 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008874 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008875 } else {
8876 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8877 "Expected to or link clauses.");
8878 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008879 }
8880 }
8881}
8882
Alexey Bataev60705422018-10-30 15:50:12 +00008883void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
8884 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
8885 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
8886 " Expected target-based directive.");
8887}
8888
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008889CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8890 CodeGenModule &CGM)
8891 : CGM(CGM) {
8892 if (CGM.getLangOpts().OpenMPIsDevice) {
8893 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8894 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8895 }
8896}
8897
8898CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8899 if (CGM.getLangOpts().OpenMPIsDevice)
8900 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8901}
8902
Alexey Bataev6d944102018-05-02 15:45:28 +00008903bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008904 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8905 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008906
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008907 StringRef Name = CGM.getMangledName(GD);
Alexey Bataev6d944102018-05-02 15:45:28 +00008908 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev34f8a702018-03-28 14:28:54 +00008909 // Do not to emit function if it is marked as declare target as it was already
8910 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008911 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008912 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
8913 if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008914 return !F->isDeclaration();
8915 return false;
8916 }
8917 return true;
8918 }
8919
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008920 return !AlreadyEmittedTargetFunctions.insert(Name).second;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008921}
8922
Samuel Antaoee8fb302016-01-06 13:42:12 +00008923llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8924 // If we have offloading in the current module, we need to emit the entries
8925 // now and register the offloading descriptor.
8926 createOffloadEntriesAndInfoMetadata();
8927
8928 // Create and register the offloading binary descriptors. This is the main
8929 // entity that captures all the information about offloading in the current
8930 // compilation unit.
8931 return createOffloadingBinaryDescriptorRegistration();
8932}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008933
8934void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8935 const OMPExecutableDirective &D,
8936 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00008937 llvm::Function *OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008938 ArrayRef<llvm::Value *> CapturedVars) {
8939 if (!CGF.HaveInsertPoint())
8940 return;
8941
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008942 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008943 CodeGenFunction::RunCleanupsScope Scope(CGF);
8944
8945 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8946 llvm::Value *Args[] = {
8947 RTLoc,
8948 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8949 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8950 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8951 RealArgs.append(std::begin(Args), std::end(Args));
8952 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8953
James Y Knight9871db02019-02-05 16:42:33 +00008954 llvm::FunctionCallee RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008955 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8956}
8957
8958void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008959 const Expr *NumTeams,
8960 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008961 SourceLocation Loc) {
8962 if (!CGF.HaveInsertPoint())
8963 return;
8964
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008965 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008966
Carlo Bertollic6872252016-04-04 15:55:02 +00008967 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008968 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008969 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8970 CGF.CGM.Int32Ty, /* isSigned = */ true)
8971 : CGF.Builder.getInt32(0);
8972
8973 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008974 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008975 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8976 CGF.CGM.Int32Ty, /* isSigned = */ true)
8977 : CGF.Builder.getInt32(0);
8978
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008979 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008980 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8981 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008982 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8983 PushNumTeamsArgs);
8984}
Samuel Antaodf158d52016-04-27 22:58:19 +00008985
Samuel Antaocc10b852016-07-28 14:23:26 +00008986void CGOpenMPRuntime::emitTargetDataCalls(
8987 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8988 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008989 if (!CGF.HaveInsertPoint())
8990 return;
8991
Samuel Antaocc10b852016-07-28 14:23:26 +00008992 // Action used to replace the default codegen action and turn privatization
8993 // off.
8994 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008995
8996 // Generate the code for the opening of the data environment. Capture all the
8997 // arguments of the runtime call by reference because they are used in the
8998 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008999 auto &&BeginThenGen = [this, &D, Device, &Info,
9000 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00009001 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00009002 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00009003 MappableExprsHandler::MapValuesArrayTy Pointers;
9004 MappableExprsHandler::MapValuesArrayTy Sizes;
9005 MappableExprsHandler::MapFlagsArrayTy MapTypes;
9006
9007 // Get map clause information.
9008 MappableExprsHandler MCHandler(D, CGF);
9009 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00009010
9011 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00009012 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00009013
9014 llvm::Value *BasePointersArrayArg = nullptr;
9015 llvm::Value *PointersArrayArg = nullptr;
9016 llvm::Value *SizesArrayArg = nullptr;
9017 llvm::Value *MapTypesArrayArg = nullptr;
9018 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00009019 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00009020
9021 // Emit device ID if any.
9022 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009023 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00009024 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009025 CGF.Int64Ty, /*isSigned=*/true);
9026 } else {
9027 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9028 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009029
9030 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009031 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00009032
9033 llvm::Value *OffloadingArgs[] = {
9034 DeviceID, PointerNum, BasePointersArrayArg,
9035 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009036 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00009037 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00009038
9039 // If device pointer privatization is required, emit the body of the region
9040 // here. It will have to be duplicated: with and without privatization.
9041 if (!Info.CaptureDeviceAddrMap.empty())
9042 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009043 };
9044
9045 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009046 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
9047 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009048 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00009049
9050 llvm::Value *BasePointersArrayArg = nullptr;
9051 llvm::Value *PointersArrayArg = nullptr;
9052 llvm::Value *SizesArrayArg = nullptr;
9053 llvm::Value *MapTypesArrayArg = nullptr;
9054 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00009055 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00009056
9057 // Emit device ID if any.
9058 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009059 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00009060 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009061 CGF.Int64Ty, /*isSigned=*/true);
9062 } else {
9063 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9064 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009065
9066 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009067 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00009068
9069 llvm::Value *OffloadingArgs[] = {
9070 DeviceID, PointerNum, BasePointersArrayArg,
9071 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009072 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00009073 OffloadingArgs);
9074 };
9075
Samuel Antaocc10b852016-07-28 14:23:26 +00009076 // If we need device pointer privatization, we need to emit the body of the
9077 // region with no privatization in the 'else' branch of the conditional.
9078 // Otherwise, we don't have to do anything.
9079 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
9080 PrePostActionTy &) {
9081 if (!Info.CaptureDeviceAddrMap.empty()) {
9082 CodeGen.setAction(NoPrivAction);
9083 CodeGen(CGF);
9084 }
9085 };
9086
9087 // We don't have to do anything to close the region if the if clause evaluates
9088 // to false.
9089 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00009090
9091 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009092 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009093 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009094 RegionCodeGenTy RCG(BeginThenGen);
9095 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009096 }
9097
Samuel Antaocc10b852016-07-28 14:23:26 +00009098 // If we don't require privatization of device pointers, we emit the body in
9099 // between the runtime calls. This avoids duplicating the body code.
9100 if (Info.CaptureDeviceAddrMap.empty()) {
9101 CodeGen.setAction(NoPrivAction);
9102 CodeGen(CGF);
9103 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009104
9105 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009106 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009107 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009108 RegionCodeGenTy RCG(EndThenGen);
9109 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009110 }
9111}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009112
Samuel Antao8d2d7302016-05-26 18:30:22 +00009113void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00009114 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9115 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009116 if (!CGF.HaveInsertPoint())
9117 return;
9118
Samuel Antao8dd66282016-04-27 23:14:30 +00009119 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00009120 isa<OMPTargetExitDataDirective>(D) ||
9121 isa<OMPTargetUpdateDirective>(D)) &&
9122 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00009123
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009124 CodeGenFunction::OMPTargetDataInfo InputInfo;
9125 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009126 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009127 auto &&ThenGen = [this, &D, Device, &InputInfo,
9128 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009129 // Emit device ID if any.
9130 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009131 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009132 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009133 CGF.Int64Ty, /*isSigned=*/true);
9134 } else {
9135 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9136 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009137
9138 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009139 llvm::Constant *PointerNum =
9140 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009141
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009142 llvm::Value *OffloadingArgs[] = {DeviceID,
9143 PointerNum,
9144 InputInfo.BasePointersArray.getPointer(),
9145 InputInfo.PointersArray.getPointer(),
9146 InputInfo.SizesArray.getPointer(),
9147 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00009148
Samuel Antao8d2d7302016-05-26 18:30:22 +00009149 // Select the right runtime function call for each expected standalone
9150 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009151 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00009152 OpenMPRTLFunction RTLFn;
9153 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00009154 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009155 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
9156 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009157 break;
9158 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009159 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
9160 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009161 break;
9162 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009163 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
9164 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009165 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009166 case OMPD_parallel:
9167 case OMPD_for:
9168 case OMPD_parallel_for:
9169 case OMPD_parallel_sections:
9170 case OMPD_for_simd:
9171 case OMPD_parallel_for_simd:
9172 case OMPD_cancel:
9173 case OMPD_cancellation_point:
9174 case OMPD_ordered:
9175 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009176 case OMPD_allocate:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009177 case OMPD_task:
9178 case OMPD_simd:
9179 case OMPD_sections:
9180 case OMPD_section:
9181 case OMPD_single:
9182 case OMPD_master:
9183 case OMPD_critical:
9184 case OMPD_taskyield:
9185 case OMPD_barrier:
9186 case OMPD_taskwait:
9187 case OMPD_taskgroup:
9188 case OMPD_atomic:
9189 case OMPD_flush:
9190 case OMPD_teams:
9191 case OMPD_target_data:
9192 case OMPD_distribute:
9193 case OMPD_distribute_simd:
9194 case OMPD_distribute_parallel_for:
9195 case OMPD_distribute_parallel_for_simd:
9196 case OMPD_teams_distribute:
9197 case OMPD_teams_distribute_simd:
9198 case OMPD_teams_distribute_parallel_for:
9199 case OMPD_teams_distribute_parallel_for_simd:
9200 case OMPD_declare_simd:
9201 case OMPD_declare_target:
9202 case OMPD_end_declare_target:
9203 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009204 case OMPD_declare_mapper:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009205 case OMPD_taskloop:
9206 case OMPD_taskloop_simd:
9207 case OMPD_target:
9208 case OMPD_target_simd:
9209 case OMPD_target_teams_distribute:
9210 case OMPD_target_teams_distribute_simd:
9211 case OMPD_target_teams_distribute_parallel_for:
9212 case OMPD_target_teams_distribute_parallel_for_simd:
9213 case OMPD_target_teams:
9214 case OMPD_target_parallel:
9215 case OMPD_target_parallel_for:
9216 case OMPD_target_parallel_for_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009217 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009218 case OMPD_unknown:
9219 llvm_unreachable("Unexpected standalone target data directive.");
9220 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009221 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009222 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009223 };
9224
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009225 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
9226 CodeGenFunction &CGF, PrePostActionTy &) {
9227 // Fill up the arrays with all the mapped variables.
9228 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
9229 MappableExprsHandler::MapValuesArrayTy Pointers;
9230 MappableExprsHandler::MapValuesArrayTy Sizes;
9231 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009232
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009233 // Get map clause information.
9234 MappableExprsHandler MEHandler(D, CGF);
9235 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
9236
9237 TargetDataInfo Info;
9238 // Fill up the arrays and create the arguments.
9239 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
9240 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
9241 Info.PointersArray, Info.SizesArray,
9242 Info.MapTypesArray, Info);
9243 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
9244 InputInfo.BasePointersArray =
9245 Address(Info.BasePointersArray, CGM.getPointerAlign());
9246 InputInfo.PointersArray =
9247 Address(Info.PointersArray, CGM.getPointerAlign());
9248 InputInfo.SizesArray =
9249 Address(Info.SizesArray, CGM.getPointerAlign());
9250 MapTypesArray = Info.MapTypesArray;
9251 if (D.hasClausesOfKind<OMPDependClause>())
9252 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
9253 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00009254 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009255 };
9256
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009257 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009258 emitOMPIfClause(CGF, IfCond, TargetThenGen,
9259 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009260 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009261 RegionCodeGenTy ThenRCG(TargetThenGen);
9262 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009263 }
9264}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009265
9266namespace {
9267 /// Kind of parameter in a function with 'declare simd' directive.
9268 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
9269 /// Attribute set of the parameter.
9270 struct ParamAttrTy {
9271 ParamKindTy Kind = Vector;
9272 llvm::APSInt StrideOrArg;
9273 llvm::APSInt Alignment;
9274 };
9275} // namespace
9276
9277static unsigned evaluateCDTSize(const FunctionDecl *FD,
9278 ArrayRef<ParamAttrTy> ParamAttrs) {
9279 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
9280 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
9281 // of that clause. The VLEN value must be power of 2.
9282 // In other case the notion of the function`s "characteristic data type" (CDT)
9283 // is used to compute the vector length.
9284 // CDT is defined in the following order:
9285 // a) For non-void function, the CDT is the return type.
9286 // b) If the function has any non-uniform, non-linear parameters, then the
9287 // CDT is the type of the first such parameter.
9288 // c) If the CDT determined by a) or b) above is struct, union, or class
9289 // type which is pass-by-value (except for the type that maps to the
9290 // built-in complex data type), the characteristic data type is int.
9291 // d) If none of the above three cases is applicable, the CDT is int.
9292 // The VLEN is then determined based on the CDT and the size of vector
9293 // register of that ISA for which current vector version is generated. The
9294 // VLEN is computed using the formula below:
9295 // VLEN = sizeof(vector_register) / sizeof(CDT),
9296 // where vector register size specified in section 3.2.1 Registers and the
9297 // Stack Frame of original AMD64 ABI document.
9298 QualType RetType = FD->getReturnType();
9299 if (RetType.isNull())
9300 return 0;
9301 ASTContext &C = FD->getASTContext();
9302 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009303 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009304 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009305 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009306 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009307 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009308 if (ParamAttrs[Offset].Kind == Vector)
9309 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
9310 ++Offset;
9311 }
9312 if (CDT.isNull()) {
9313 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
9314 if (ParamAttrs[I + Offset].Kind == Vector) {
9315 CDT = FD->getParamDecl(I)->getType();
9316 break;
9317 }
9318 }
9319 }
9320 }
9321 if (CDT.isNull())
9322 CDT = C.IntTy;
9323 CDT = CDT->getCanonicalTypeUnqualified();
9324 if (CDT->isRecordType() || CDT->isUnionType())
9325 CDT = C.IntTy;
9326 return C.getTypeSize(CDT);
9327}
9328
9329static void
9330emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00009331 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009332 ArrayRef<ParamAttrTy> ParamAttrs,
9333 OMPDeclareSimdDeclAttr::BranchStateTy State) {
9334 struct ISADataTy {
9335 char ISA;
9336 unsigned VecRegSize;
9337 };
9338 ISADataTy ISAData[] = {
9339 {
9340 'b', 128
9341 }, // SSE
9342 {
9343 'c', 256
9344 }, // AVX
9345 {
9346 'd', 256
9347 }, // AVX2
9348 {
9349 'e', 512
9350 }, // AVX512
9351 };
9352 llvm::SmallVector<char, 2> Masked;
9353 switch (State) {
9354 case OMPDeclareSimdDeclAttr::BS_Undefined:
9355 Masked.push_back('N');
9356 Masked.push_back('M');
9357 break;
9358 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
9359 Masked.push_back('N');
9360 break;
9361 case OMPDeclareSimdDeclAttr::BS_Inbranch:
9362 Masked.push_back('M');
9363 break;
9364 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009365 for (char Mask : Masked) {
9366 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009367 SmallString<256> Buffer;
9368 llvm::raw_svector_ostream Out(Buffer);
9369 Out << "_ZGV" << Data.ISA << Mask;
9370 if (!VLENVal) {
9371 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
9372 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009373 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009374 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009375 }
9376 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009377 switch (ParamAttr.Kind){
9378 case LinearWithVarStride:
9379 Out << 's' << ParamAttr.StrideOrArg;
9380 break;
9381 case Linear:
9382 Out << 'l';
9383 if (!!ParamAttr.StrideOrArg)
9384 Out << ParamAttr.StrideOrArg;
9385 break;
9386 case Uniform:
9387 Out << 'u';
9388 break;
9389 case Vector:
9390 Out << 'v';
9391 break;
9392 }
9393 if (!!ParamAttr.Alignment)
9394 Out << 'a' << ParamAttr.Alignment;
9395 }
9396 Out << '_' << Fn->getName();
9397 Fn->addFnAttr(Out.str());
9398 }
9399 }
9400}
9401
9402void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
9403 llvm::Function *Fn) {
9404 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009405 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009406 // Map params to their positions in function decl.
9407 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
9408 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009409 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009410 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009411 for (const ParmVarDecl *P : FD->parameters()) {
9412 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009413 ++ParamPos;
9414 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009415 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009416 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009417 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
9418 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009419 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009420 E = E->IgnoreParenImpCasts();
9421 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009422 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009423 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009424 } else {
9425 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9426 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009427 Pos = ParamPositions[PVD];
9428 }
9429 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009430 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009431 // Get alignment info.
9432 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009433 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009434 E = E->IgnoreParenImpCasts();
9435 unsigned Pos;
9436 QualType ParmTy;
9437 if (isa<CXXThisExpr>(E)) {
9438 Pos = ParamPositions[FD];
9439 ParmTy = E->getType();
9440 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009441 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9442 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009443 Pos = ParamPositions[PVD];
9444 ParmTy = PVD->getType();
9445 }
9446 ParamAttrs[Pos].Alignment =
9447 (*NI)
9448 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009449 : llvm::APSInt::getUnsigned(
9450 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
9451 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009452 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009453 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009454 // Mark linear parameters.
9455 auto SI = Attr->steps_begin();
9456 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009457 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009458 E = E->IgnoreParenImpCasts();
9459 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009460 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009461 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009462 } else {
9463 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9464 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009465 Pos = ParamPositions[PVD];
9466 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009467 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009468 ParamAttr.Kind = Linear;
9469 if (*SI) {
Fangrui Song407659a2018-11-30 23:41:18 +00009470 Expr::EvalResult Result;
9471 if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009472 if (const auto *DRE =
9473 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9474 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009475 ParamAttr.Kind = LinearWithVarStride;
9476 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9477 ParamPositions[StridePVD->getCanonicalDecl()]);
9478 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009479 }
Fangrui Song407659a2018-11-30 23:41:18 +00009480 } else {
9481 ParamAttr.StrideOrArg = Result.Val.getInt();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009482 }
9483 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009484 ++SI;
9485 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009486 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009487 llvm::APSInt VLENVal;
9488 if (const Expr *VLEN = Attr->getSimdlen())
9489 VLENVal = VLEN->EvaluateKnownConstInt(C);
9490 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9491 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9492 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9493 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009494 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009495 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009496 }
9497}
Alexey Bataev8b427062016-05-25 12:36:08 +00009498
9499namespace {
9500/// Cleanup action for doacross support.
9501class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9502public:
9503 static const int DoacrossFinArgs = 2;
9504
9505private:
James Y Knight9871db02019-02-05 16:42:33 +00009506 llvm::FunctionCallee RTLFn;
Alexey Bataev8b427062016-05-25 12:36:08 +00009507 llvm::Value *Args[DoacrossFinArgs];
9508
9509public:
James Y Knight9871db02019-02-05 16:42:33 +00009510 DoacrossCleanupTy(llvm::FunctionCallee RTLFn,
9511 ArrayRef<llvm::Value *> CallArgs)
Alexey Bataev8b427062016-05-25 12:36:08 +00009512 : RTLFn(RTLFn) {
9513 assert(CallArgs.size() == DoacrossFinArgs);
9514 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9515 }
9516 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9517 if (!CGF.HaveInsertPoint())
9518 return;
9519 CGF.EmitRuntimeCall(RTLFn, Args);
9520 }
9521};
9522} // namespace
9523
9524void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009525 const OMPLoopDirective &D,
9526 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009527 if (!CGF.HaveInsertPoint())
9528 return;
9529
9530 ASTContext &C = CGM.getContext();
9531 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9532 RecordDecl *RD;
9533 if (KmpDimTy.isNull()) {
9534 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9535 // kmp_int64 lo; // lower
9536 // kmp_int64 up; // upper
9537 // kmp_int64 st; // stride
9538 // };
9539 RD = C.buildImplicitRecord("kmp_dim");
9540 RD->startDefinition();
9541 addFieldToRecordDecl(C, RD, Int64Ty);
9542 addFieldToRecordDecl(C, RD, Int64Ty);
9543 addFieldToRecordDecl(C, RD, Int64Ty);
9544 RD->completeDefinition();
9545 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009546 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009547 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009548 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009549 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9550 QualType ArrayTy =
9551 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009552
Alexey Bataevf138fda2018-08-13 19:04:24 +00009553 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9554 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009555 enum { LowerFD = 0, UpperFD, StrideFD };
9556 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009557 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
James Y Knight751fe282019-02-09 22:22:28 +00009558 LValue DimsLVal = CGF.MakeAddrLValue(
9559 CGF.Builder.CreateConstArrayGEP(DimsAddr, I), KmpDimTy);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009560 // dims.upper = num_iterations;
9561 LValue UpperLVal = CGF.EmitLValueForField(
9562 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9563 llvm::Value *NumIterVal =
9564 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9565 D.getNumIterations()->getType(), Int64Ty,
9566 D.getNumIterations()->getExprLoc());
9567 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9568 // dims.stride = 1;
9569 LValue StrideLVal = CGF.EmitLValueForField(
9570 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9571 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9572 StrideLVal);
9573 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009574
9575 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9576 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009577 llvm::Value *Args[] = {
9578 emitUpdateLocation(CGF, D.getBeginLoc()),
9579 getThreadID(CGF, D.getBeginLoc()),
9580 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9581 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00009582 CGF.Builder.CreateConstArrayGEP(DimsAddr, 0).getPointer(),
Alexey Bataevf138fda2018-08-13 19:04:24 +00009583 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009584
James Y Knight9871db02019-02-05 16:42:33 +00009585 llvm::FunctionCallee RTLFn =
9586 createRuntimeFunction(OMPRTL__kmpc_doacross_init);
Alexey Bataev8b427062016-05-25 12:36:08 +00009587 CGF.EmitRuntimeCall(RTLFn, Args);
9588 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009589 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
James Y Knight9871db02019-02-05 16:42:33 +00009590 llvm::FunctionCallee FiniRTLFn =
9591 createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
Alexey Bataev8b427062016-05-25 12:36:08 +00009592 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9593 llvm::makeArrayRef(FiniArgs));
9594}
9595
9596void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9597 const OMPDependClause *C) {
9598 QualType Int64Ty =
9599 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009600 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9601 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9602 Int64Ty, Size, ArrayType::Normal, 0);
9603 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9604 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9605 const Expr *CounterVal = C->getLoopData(I);
9606 assert(CounterVal);
9607 llvm::Value *CntVal = CGF.EmitScalarConversion(
9608 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9609 CounterVal->getExprLoc());
James Y Knight751fe282019-02-09 22:22:28 +00009610 CGF.EmitStoreOfScalar(CntVal, CGF.Builder.CreateConstArrayGEP(CntAddr, I),
9611 /*Volatile=*/false, Int64Ty);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009612 }
9613 llvm::Value *Args[] = {
9614 emitUpdateLocation(CGF, C->getBeginLoc()),
9615 getThreadID(CGF, C->getBeginLoc()),
James Y Knight751fe282019-02-09 22:22:28 +00009616 CGF.Builder.CreateConstArrayGEP(CntAddr, 0).getPointer()};
James Y Knight9871db02019-02-05 16:42:33 +00009617 llvm::FunctionCallee RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009618 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009619 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009620 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009621 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9622 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9623 }
9624 CGF.EmitRuntimeCall(RTLFn, Args);
9625}
9626
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009627void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00009628 llvm::FunctionCallee Callee,
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009629 ArrayRef<llvm::Value *> Args) const {
9630 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009631 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9632
James Y Knight9871db02019-02-05 16:42:33 +00009633 if (auto *Fn = dyn_cast<llvm::Function>(Callee.getCallee())) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009634 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009635 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009636 return;
9637 }
9638 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009639 CGF.EmitRuntimeCall(Callee, Args);
9640}
9641
9642void CGOpenMPRuntime::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00009643 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3c595a62017-08-14 15:01:03 +00009644 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009645 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009646}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009647
9648Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9649 const VarDecl *NativeParam,
9650 const VarDecl *TargetParam) const {
9651 return CGF.GetAddrOfLocalVar(NativeParam);
9652}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009653
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009654Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9655 const VarDecl *VD) {
9656 return Address::invalid();
9657}
9658
James Y Knight9871db02019-02-05 16:42:33 +00009659llvm::Function *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009660 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9661 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9662 llvm_unreachable("Not supported in SIMD-only mode");
9663}
9664
James Y Knight9871db02019-02-05 16:42:33 +00009665llvm::Function *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009666 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9667 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9668 llvm_unreachable("Not supported in SIMD-only mode");
9669}
9670
James Y Knight9871db02019-02-05 16:42:33 +00009671llvm::Function *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009672 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9673 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9674 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9675 bool Tied, unsigned &NumberOfParts) {
9676 llvm_unreachable("Not supported in SIMD-only mode");
9677}
9678
9679void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9680 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00009681 llvm::Function *OutlinedFn,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009682 ArrayRef<llvm::Value *> CapturedVars,
9683 const Expr *IfCond) {
9684 llvm_unreachable("Not supported in SIMD-only mode");
9685}
9686
9687void CGOpenMPSIMDRuntime::emitCriticalRegion(
9688 CodeGenFunction &CGF, StringRef CriticalName,
9689 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9690 const Expr *Hint) {
9691 llvm_unreachable("Not supported in SIMD-only mode");
9692}
9693
9694void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9695 const RegionCodeGenTy &MasterOpGen,
9696 SourceLocation Loc) {
9697 llvm_unreachable("Not supported in SIMD-only mode");
9698}
9699
9700void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9701 SourceLocation Loc) {
9702 llvm_unreachable("Not supported in SIMD-only mode");
9703}
9704
9705void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9706 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9707 SourceLocation Loc) {
9708 llvm_unreachable("Not supported in SIMD-only mode");
9709}
9710
9711void CGOpenMPSIMDRuntime::emitSingleRegion(
9712 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9713 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9714 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9715 ArrayRef<const Expr *> AssignmentOps) {
9716 llvm_unreachable("Not supported in SIMD-only mode");
9717}
9718
9719void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9720 const RegionCodeGenTy &OrderedOpGen,
9721 SourceLocation Loc,
9722 bool IsThreads) {
9723 llvm_unreachable("Not supported in SIMD-only mode");
9724}
9725
9726void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9727 SourceLocation Loc,
9728 OpenMPDirectiveKind Kind,
9729 bool EmitChecks,
9730 bool ForceSimpleCall) {
9731 llvm_unreachable("Not supported in SIMD-only mode");
9732}
9733
9734void CGOpenMPSIMDRuntime::emitForDispatchInit(
9735 CodeGenFunction &CGF, SourceLocation Loc,
9736 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9737 bool Ordered, const DispatchRTInput &DispatchValues) {
9738 llvm_unreachable("Not supported in SIMD-only mode");
9739}
9740
9741void CGOpenMPSIMDRuntime::emitForStaticInit(
9742 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9743 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9744 llvm_unreachable("Not supported in SIMD-only mode");
9745}
9746
9747void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9748 CodeGenFunction &CGF, SourceLocation Loc,
9749 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9750 llvm_unreachable("Not supported in SIMD-only mode");
9751}
9752
9753void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9754 SourceLocation Loc,
9755 unsigned IVSize,
9756 bool IVSigned) {
9757 llvm_unreachable("Not supported in SIMD-only mode");
9758}
9759
9760void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9761 SourceLocation Loc,
9762 OpenMPDirectiveKind DKind) {
9763 llvm_unreachable("Not supported in SIMD-only mode");
9764}
9765
9766llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9767 SourceLocation Loc,
9768 unsigned IVSize, bool IVSigned,
9769 Address IL, Address LB,
9770 Address UB, Address ST) {
9771 llvm_unreachable("Not supported in SIMD-only mode");
9772}
9773
9774void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9775 llvm::Value *NumThreads,
9776 SourceLocation Loc) {
9777 llvm_unreachable("Not supported in SIMD-only mode");
9778}
9779
9780void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9781 OpenMPProcBindClauseKind ProcBind,
9782 SourceLocation Loc) {
9783 llvm_unreachable("Not supported in SIMD-only mode");
9784}
9785
9786Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9787 const VarDecl *VD,
9788 Address VDAddr,
9789 SourceLocation Loc) {
9790 llvm_unreachable("Not supported in SIMD-only mode");
9791}
9792
9793llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9794 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9795 CodeGenFunction *CGF) {
9796 llvm_unreachable("Not supported in SIMD-only mode");
9797}
9798
9799Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9800 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9801 llvm_unreachable("Not supported in SIMD-only mode");
9802}
9803
9804void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9805 ArrayRef<const Expr *> Vars,
9806 SourceLocation Loc) {
9807 llvm_unreachable("Not supported in SIMD-only mode");
9808}
9809
9810void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9811 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00009812 llvm::Function *TaskFunction,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009813 QualType SharedsTy, Address Shareds,
9814 const Expr *IfCond,
9815 const OMPTaskDataTy &Data) {
9816 llvm_unreachable("Not supported in SIMD-only mode");
9817}
9818
9819void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9820 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00009821 llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009822 const Expr *IfCond, const OMPTaskDataTy &Data) {
9823 llvm_unreachable("Not supported in SIMD-only mode");
9824}
9825
9826void CGOpenMPSIMDRuntime::emitReduction(
9827 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9828 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9829 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9830 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9831 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9832 ReductionOps, Options);
9833}
9834
9835llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9836 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9837 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9838 llvm_unreachable("Not supported in SIMD-only mode");
9839}
9840
9841void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9842 SourceLocation Loc,
9843 ReductionCodeGen &RCG,
9844 unsigned N) {
9845 llvm_unreachable("Not supported in SIMD-only mode");
9846}
9847
9848Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9849 SourceLocation Loc,
9850 llvm::Value *ReductionsPtr,
9851 LValue SharedLVal) {
9852 llvm_unreachable("Not supported in SIMD-only mode");
9853}
9854
9855void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9856 SourceLocation Loc) {
9857 llvm_unreachable("Not supported in SIMD-only mode");
9858}
9859
9860void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9861 CodeGenFunction &CGF, SourceLocation Loc,
9862 OpenMPDirectiveKind CancelRegion) {
9863 llvm_unreachable("Not supported in SIMD-only mode");
9864}
9865
9866void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9867 SourceLocation Loc, const Expr *IfCond,
9868 OpenMPDirectiveKind CancelRegion) {
9869 llvm_unreachable("Not supported in SIMD-only mode");
9870}
9871
9872void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9873 const OMPExecutableDirective &D, StringRef ParentName,
9874 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9875 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9876 llvm_unreachable("Not supported in SIMD-only mode");
9877}
9878
9879void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9880 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00009881 llvm::Function *OutlinedFn,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009882 llvm::Value *OutlinedFnID,
James Y Knight9871db02019-02-05 16:42:33 +00009883 const Expr *IfCond,
9884 const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009885 llvm_unreachable("Not supported in SIMD-only mode");
9886}
9887
9888bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9889 llvm_unreachable("Not supported in SIMD-only mode");
9890}
9891
9892bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9893 llvm_unreachable("Not supported in SIMD-only mode");
9894}
9895
9896bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9897 return false;
9898}
9899
9900llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9901 return nullptr;
9902}
9903
9904void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9905 const OMPExecutableDirective &D,
9906 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00009907 llvm::Function *OutlinedFn,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009908 ArrayRef<llvm::Value *> CapturedVars) {
9909 llvm_unreachable("Not supported in SIMD-only mode");
9910}
9911
9912void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9913 const Expr *NumTeams,
9914 const Expr *ThreadLimit,
9915 SourceLocation Loc) {
9916 llvm_unreachable("Not supported in SIMD-only mode");
9917}
9918
9919void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9920 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9921 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9922 llvm_unreachable("Not supported in SIMD-only mode");
9923}
9924
9925void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9926 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9927 const Expr *Device) {
9928 llvm_unreachable("Not supported in SIMD-only mode");
9929}
9930
9931void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009932 const OMPLoopDirective &D,
9933 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009934 llvm_unreachable("Not supported in SIMD-only mode");
9935}
9936
9937void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9938 const OMPDependClause *C) {
9939 llvm_unreachable("Not supported in SIMD-only mode");
9940}
9941
9942const VarDecl *
9943CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9944 const VarDecl *NativeParam) const {
9945 llvm_unreachable("Not supported in SIMD-only mode");
9946}
9947
9948Address
9949CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9950 const VarDecl *NativeParam,
9951 const VarDecl *TargetParam) const {
9952 llvm_unreachable("Not supported in SIMD-only mode");
9953}