blob: 67465c1acf0ab9d3714354cdc8699a7f505ac8e8 [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 Bataev4f680db2019-03-19 16:41:16 +0000670 // Call to void *__kmpc_alloc(int gtid, size_t sz, const omp_allocator_t *al);
671 OMPRTL__kmpc_alloc,
672 // Call to void __kmpc_free(int gtid, void *ptr, const omp_allocator_t *al);
673 OMPRTL__kmpc_free,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000674
675 //
676 // Offloading related calls
677 //
Alexey Bataev7bb33532019-01-07 21:30:43 +0000678 // Call to void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
679 // size);
680 OMPRTL__kmpc_push_target_tripcount,
George Rokos63bc9d62017-11-21 18:25:12 +0000681 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
682 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000683 // *arg_types);
684 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000685 // Call to int32_t __tgt_target_nowait(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);
688 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000689 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
690 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
691 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000692 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000693 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
694 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
695 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
696 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000697 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
698 OMPRTL__tgt_register_lib,
699 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
700 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000701 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
702 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000703 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000704 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
705 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
706 // *arg_types);
707 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000708 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
709 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000710 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000711 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
712 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
713 // *arg_types);
714 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000715 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
716 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000717 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000718 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
719 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
720 // *arg_types);
721 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000722};
723
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000724/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
725/// region.
726class CleanupTy final : public EHScopeStack::Cleanup {
727 PrePostActionTy *Action;
728
729public:
730 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
731 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
732 if (!CGF.HaveInsertPoint())
733 return;
734 Action->Exit(CGF);
735 }
736};
737
Hans Wennborg7eb54642015-09-10 17:07:54 +0000738} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000739
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000740void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
741 CodeGenFunction::RunCleanupsScope Scope(CGF);
742 if (PrePostAction) {
743 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
744 Callback(CodeGen, CGF, *PrePostAction);
745 } else {
746 PrePostActionTy Action;
747 Callback(CodeGen, CGF, Action);
748 }
749}
750
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000751/// Check if the combiner is a call to UDR combiner and if it is so return the
752/// UDR decl used for reduction.
753static const OMPDeclareReductionDecl *
754getReductionInit(const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000755 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
756 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
757 if (const auto *DRE =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000758 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000759 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000760 return DRD;
761 return nullptr;
762}
763
764static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
765 const OMPDeclareReductionDecl *DRD,
766 const Expr *InitOp,
767 Address Private, Address Original,
768 QualType Ty) {
769 if (DRD->getInitializer()) {
770 std::pair<llvm::Function *, llvm::Function *> Reduction =
771 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000772 const auto *CE = cast<CallExpr>(InitOp);
773 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000774 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
775 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000776 const auto *LHSDRE =
777 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
778 const auto *RHSDRE =
779 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000780 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
781 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000782 [=]() { return Private; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000783 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000784 [=]() { return Original; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000785 (void)PrivateScope.Privatize();
786 RValue Func = RValue::get(Reduction.second);
787 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
788 CGF.EmitIgnoredExpr(InitOp);
789 } else {
790 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
Alexey Bataev18fa2322018-05-02 14:20:50 +0000791 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000792 auto *GV = new llvm::GlobalVariable(
793 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
Alexey Bataev18fa2322018-05-02 14:20:50 +0000794 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000795 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
796 RValue InitRVal;
797 switch (CGF.getEvaluationKind(Ty)) {
798 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000799 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000800 break;
801 case TEK_Complex:
802 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000803 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000804 break;
805 case TEK_Aggregate:
806 InitRVal = RValue::getAggregate(LV.getAddress());
807 break;
808 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000809 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000810 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
811 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
812 /*IsInitializer=*/false);
813 }
814}
815
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000816/// Emit initialization of arrays of complex types.
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000817/// \param DestAddr Address of the array.
818/// \param Type Type of array.
819/// \param Init Initial expression of array.
820/// \param SrcAddr Address of the original array.
821static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000822 QualType Type, bool EmitDeclareReductionInit,
823 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000824 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000825 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000826 // Perform element-by-element initialization.
827 QualType ElementTy;
828
829 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000830 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
831 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000832 DestAddr =
833 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
834 if (DRD)
835 SrcAddr =
836 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
837
838 llvm::Value *SrcBegin = nullptr;
839 if (DRD)
840 SrcBegin = SrcAddr.getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000841 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000842 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000843 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000844 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000845 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
846 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
847 llvm::Value *IsEmpty =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000848 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
849 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
850
851 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000852 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000853 CGF.EmitBlock(BodyBB);
854
855 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
856
857 llvm::PHINode *SrcElementPHI = nullptr;
858 Address SrcElementCurrent = Address::invalid();
859 if (DRD) {
860 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
861 "omp.arraycpy.srcElementPast");
862 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
863 SrcElementCurrent =
864 Address(SrcElementPHI,
865 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
866 }
867 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
868 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
869 DestElementPHI->addIncoming(DestBegin, EntryBB);
870 Address DestElementCurrent =
871 Address(DestElementPHI,
872 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
873
874 // Emit copy.
875 {
876 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000877 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000878 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
879 SrcElementCurrent, ElementTy);
880 } else
881 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
882 /*IsInitializer=*/false);
883 }
884
885 if (DRD) {
886 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000887 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000888 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
889 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
890 }
891
892 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000893 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000894 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
895 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000896 llvm::Value *Done =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000897 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
898 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
899 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
900
901 // Done.
902 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
903}
904
905LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000906 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000907}
908
909LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
910 const Expr *E) {
911 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
912 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
913 return LValue();
914}
915
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000916void ReductionCodeGen::emitAggregateInitialization(
917 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
918 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000919 // Emit VarDecl with copy init for arrays.
920 // Get the address of the original variable captured in current
921 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000922 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000923 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000924 bool EmitDeclareReductionInit =
925 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000926 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000927 EmitDeclareReductionInit,
928 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
929 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000930 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000931}
932
933ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
934 ArrayRef<const Expr *> Privates,
935 ArrayRef<const Expr *> ReductionOps) {
936 ClausesData.reserve(Shareds.size());
937 SharedAddresses.reserve(Shareds.size());
938 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000939 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 auto IPriv = Privates.begin();
941 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000942 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000943 ClausesData.emplace_back(Ref, *IPriv, *IRed);
944 std::advance(IPriv, 1);
945 std::advance(IRed, 1);
946 }
947}
948
949void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
950 assert(SharedAddresses.size() == N &&
951 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000952 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
953 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
954 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000955}
956
957void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000958 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000959 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
960 QualType PrivateType = PrivateVD->getType();
961 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000962 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000963 Sizes.emplace_back(
964 CGF.getTypeSize(
965 SharedAddresses[N].first.getType().getNonReferenceType()),
966 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000967 return;
968 }
969 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000970 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000971 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000972 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
973 ->getElementType();
974 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000975 if (AsArraySection) {
976 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
977 SharedAddresses[N].first.getPointer());
978 Size = CGF.Builder.CreateNUWAdd(
979 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000980 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000981 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000982 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000983 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000984 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000985 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000986 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000987 CodeGenFunction::OpaqueValueMapping OpaqueMap(
988 CGF,
989 cast<OpaqueValueExpr>(
990 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
991 RValue::get(Size));
992 CGF.EmitVariablyModifiedType(PrivateType);
993}
994
995void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
996 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000997 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000998 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
999 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001000 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001001 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001002 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001003 "items.");
1004 return;
1005 }
1006 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1007 CGF,
1008 cast<OpaqueValueExpr>(
1009 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1010 RValue::get(Size));
1011 CGF.EmitVariablyModifiedType(PrivateType);
1012}
1013
1014void ReductionCodeGen::emitInitialization(
1015 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1016 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1017 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001018 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001019 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001020 const OMPDeclareReductionDecl *DRD =
1021 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001022 QualType PrivateType = PrivateVD->getType();
1023 PrivateAddr = CGF.Builder.CreateElementBitCast(
1024 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1025 QualType SharedType = SharedAddresses[N].first.getType();
1026 SharedLVal = CGF.MakeAddrLValue(
1027 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1028 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001029 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001030 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001031 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001032 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001033 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1034 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1035 PrivateAddr, SharedLVal.getAddress(),
1036 SharedLVal.getType());
1037 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1038 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1039 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1040 PrivateVD->getType().getQualifiers(),
1041 /*IsInitializer=*/false);
1042 }
1043}
1044
1045bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001046 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001047 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1048 QualType PrivateType = PrivateVD->getType();
1049 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1050 return DTorKind != QualType::DK_none;
1051}
1052
1053void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1054 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001055 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001056 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1057 QualType PrivateType = PrivateVD->getType();
1058 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1059 if (needCleanups(N)) {
1060 PrivateAddr = CGF.Builder.CreateElementBitCast(
1061 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1062 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1063 }
1064}
1065
1066static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1067 LValue BaseLV) {
1068 BaseTy = BaseTy.getNonReferenceType();
1069 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1070 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001071 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001072 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001073 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001074 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1075 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001076 }
1077 BaseTy = BaseTy->getPointeeType();
1078 }
1079 return CGF.MakeAddrLValue(
1080 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1081 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001082 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001083 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001084}
1085
1086static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1087 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1088 llvm::Value *Addr) {
1089 Address Tmp = Address::invalid();
1090 Address TopTmp = Address::invalid();
1091 Address MostTopTmp = Address::invalid();
1092 BaseTy = BaseTy.getNonReferenceType();
1093 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1094 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1095 Tmp = CGF.CreateMemTemp(BaseTy);
1096 if (TopTmp.isValid())
1097 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1098 else
1099 MostTopTmp = Tmp;
1100 TopTmp = Tmp;
1101 BaseTy = BaseTy->getPointeeType();
1102 }
1103 llvm::Type *Ty = BaseLVType;
1104 if (Tmp.isValid())
1105 Ty = Tmp.getElementType();
1106 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1107 if (Tmp.isValid()) {
1108 CGF.Builder.CreateStore(Addr, Tmp);
1109 return MostTopTmp;
1110 }
1111 return Address(Addr, BaseLVAlignment);
1112}
1113
Alexey Bataev1c44e152018-03-06 18:59:43 +00001114static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001115 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001116 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1117 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1118 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001119 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001120 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001121 Base = TempASE->getBase()->IgnoreParenImpCasts();
1122 DE = cast<DeclRefExpr>(Base);
1123 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001124 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1125 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1126 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001127 Base = TempASE->getBase()->IgnoreParenImpCasts();
1128 DE = cast<DeclRefExpr>(Base);
1129 OrigVD = cast<VarDecl>(DE->getDecl());
1130 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001131 return OrigVD;
1132}
1133
1134Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1135 Address PrivateAddr) {
1136 const DeclRefExpr *DE;
1137 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001138 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001139 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001140 LValue BaseLValue =
1141 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1142 OriginalBaseLValue);
1143 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1144 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001145 llvm::Value *PrivatePointer =
1146 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1147 PrivateAddr.getPointer(),
1148 SharedAddresses[N].first.getAddress().getType());
1149 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001150 return castToBase(CGF, OrigVD->getType(),
1151 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001152 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001153 OriginalBaseLValue.getAlignment(), Ptr);
1154 }
1155 BaseDecls.emplace_back(
1156 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1157 return PrivateAddr;
1158}
1159
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001160bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001161 const OMPDeclareReductionDecl *DRD =
1162 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001163 return DRD && DRD->getInitializer();
1164}
1165
Alexey Bataev18095712014-10-10 12:19:54 +00001166LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001167 return CGF.EmitLoadOfPointerLValue(
1168 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1169 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001170}
1171
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001172void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001173 if (!CGF.HaveInsertPoint())
1174 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001175 // 1.2.2 OpenMP Language Terminology
1176 // Structured block - An executable statement with a single entry at the
1177 // top and a single exit at the bottom.
1178 // The point of exit cannot be a branch out of the structured block.
1179 // longjmp() and throw() must not violate the entry/exit criteria.
1180 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001181 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001182 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001183}
1184
Alexey Bataev62b63b12015-03-10 07:28:44 +00001185LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1186 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001187 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1188 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001189 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001190}
1191
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001192static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1193 QualType FieldTy) {
1194 auto *Field = FieldDecl::Create(
1195 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1196 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1197 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1198 Field->setAccess(AS_public);
1199 DC->addDecl(Field);
1200 return Field;
1201}
1202
Alexey Bataev18fa2322018-05-02 14:20:50 +00001203CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1204 StringRef Separator)
1205 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1206 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001207 ASTContext &C = CGM.getContext();
1208 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1209 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1210 RD->startDefinition();
1211 // reserved_1
1212 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1213 // flags
1214 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1215 // reserved_2
1216 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1217 // reserved_3
1218 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1219 // psource
1220 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1221 RD->completeDefinition();
1222 IdentQTy = C.getRecordType(RD);
1223 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001224 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001225
1226 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001227}
1228
Alexey Bataev91797552015-03-18 04:13:55 +00001229void CGOpenMPRuntime::clear() {
1230 InternalVars.clear();
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00001231 // Clean non-target variable declarations possibly used only in debug info.
1232 for (const auto &Data : EmittedNonTargetVariables) {
1233 if (!Data.getValue().pointsToAliveValue())
1234 continue;
1235 auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
1236 if (!GV)
1237 continue;
1238 if (!GV->isDeclaration() || GV->getNumUses() > 0)
1239 continue;
1240 GV->eraseFromParent();
1241 }
Alexey Bataev91797552015-03-18 04:13:55 +00001242}
1243
Alexey Bataev18fa2322018-05-02 14:20:50 +00001244std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1245 SmallString<128> Buffer;
1246 llvm::raw_svector_ostream OS(Buffer);
1247 StringRef Sep = FirstSeparator;
1248 for (StringRef Part : Parts) {
1249 OS << Sep << Part;
1250 Sep = Separator;
1251 }
1252 return OS.str();
1253}
1254
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001255static llvm::Function *
1256emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1257 const Expr *CombinerInitializer, const VarDecl *In,
1258 const VarDecl *Out, bool IsCombiner) {
1259 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001260 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001261 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1262 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001263 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001264 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001265 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001266 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001267 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001268 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001269 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001270 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001271 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001272 std::string Name = CGM.getOpenMPRuntime().getName(
1273 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1274 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1275 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001276 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001277 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001278 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001279 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001280 CodeGenFunction CGF(CGM);
1281 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1282 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001283 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1284 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001285 CodeGenFunction::OMPPrivateScope Scope(CGF);
1286 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001287 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001288 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1289 .getAddress();
1290 });
1291 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001292 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001293 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1294 .getAddress();
1295 });
1296 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001297 if (!IsCombiner && Out->hasInit() &&
1298 !CGF.isTrivialInitializer(Out->getInit())) {
1299 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1300 Out->getType().getQualifiers(),
1301 /*IsInitializer=*/true);
1302 }
1303 if (CombinerInitializer)
1304 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001305 Scope.ForceCleanup();
1306 CGF.FinishFunction();
1307 return Fn;
1308}
1309
1310void CGOpenMPRuntime::emitUserDefinedReduction(
1311 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1312 if (UDRMap.count(D) > 0)
1313 return;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001314 llvm::Function *Combiner = emitCombinerOrInitializer(
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001315 CGM, D->getType(), D->getCombiner(),
1316 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1317 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001318 /*IsCombiner=*/true);
1319 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001320 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001321 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001322 CGM, D->getType(),
1323 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1324 : nullptr,
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001325 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1326 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001327 /*IsCombiner=*/false);
1328 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001329 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001330 if (CGF) {
1331 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1332 Decls.second.push_back(D);
1333 }
1334}
1335
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001336std::pair<llvm::Function *, llvm::Function *>
1337CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1338 auto I = UDRMap.find(D);
1339 if (I != UDRMap.end())
1340 return I->second;
1341 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1342 return UDRMap.lookup(D);
1343}
1344
James Y Knight9871db02019-02-05 16:42:33 +00001345static llvm::Function *emitParallelOrTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001346 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1347 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1348 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001349 assert(ThreadIDVar->getType()->isPointerType() &&
1350 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001351 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001352 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001353 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001354 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001355 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001356 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001357 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001358 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001359 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001360 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001361 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001362 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001363 else if (const auto *OPFD =
1364 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001365 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001366 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001367 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1368 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001369 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001370 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001371 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001372 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001373}
1374
James Y Knight9871db02019-02-05 16:42:33 +00001375llvm::Function *CGOpenMPRuntime::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001376 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1377 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1378 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1379 return emitParallelOrTeamsOutlinedFunction(
1380 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1381}
1382
James Y Knight9871db02019-02-05 16:42:33 +00001383llvm::Function *CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001384 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1385 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1386 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1387 return emitParallelOrTeamsOutlinedFunction(
1388 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1389}
1390
James Y Knight9871db02019-02-05 16:42:33 +00001391llvm::Function *CGOpenMPRuntime::emitTaskOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001392 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001393 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1394 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1395 bool Tied, unsigned &NumberOfParts) {
1396 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1397 PrePostActionTy &) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001398 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1399 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001400 llvm::Value *TaskArgs[] = {
1401 UpLoc, ThreadID,
1402 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1403 TaskTVar->getType()->castAs<PointerType>())
1404 .getPointer()};
1405 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1406 };
1407 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1408 UntiedCodeGen);
1409 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001410 assert(!ThreadIDVar->getType()->isPointerType() &&
1411 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001412 const OpenMPDirectiveKind Region =
1413 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1414 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001415 const CapturedStmt *CS = D.getCapturedStmt(Region);
1416 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001417 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001418 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1419 InnermostKind,
1420 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001421 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
James Y Knight9871db02019-02-05 16:42:33 +00001422 llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001423 if (!Tied)
1424 NumberOfParts = Action.getNumberOfParts();
1425 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001426}
1427
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001428static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1429 const RecordDecl *RD, const CGRecordLayout &RL,
1430 ArrayRef<llvm::Constant *> Data) {
1431 llvm::StructType *StructTy = RL.getLLVMType();
1432 unsigned PrevIdx = 0;
1433 ConstantInitBuilder CIBuilder(CGM);
1434 auto DI = Data.begin();
1435 for (const FieldDecl *FD : RD->fields()) {
1436 unsigned Idx = RL.getLLVMFieldNo(FD);
1437 // Fill the alignment.
1438 for (unsigned I = PrevIdx; I < Idx; ++I)
1439 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1440 PrevIdx = Idx + 1;
1441 Fields.add(*DI);
1442 ++DI;
1443 }
1444}
1445
1446template <class... As>
1447static llvm::GlobalVariable *
Mike Ricee1ca7b62018-08-29 15:45:11 +00001448createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
1449 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1450 As &&... Args) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001451 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1452 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1453 ConstantInitBuilder CIBuilder(CGM);
1454 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1455 buildStructValue(Fields, CGM, RD, RL, Data);
1456 return Fields.finishAndCreateGlobal(
Mike Ricee1ca7b62018-08-29 15:45:11 +00001457 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
1458 std::forward<As>(Args)...);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001459}
1460
1461template <typename T>
Benjamin Kramer651d0bf2018-05-15 21:26:47 +00001462static void
1463createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1464 ArrayRef<llvm::Constant *> Data,
1465 T &Parent) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001466 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1467 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1468 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1469 buildStructValue(Fields, CGM, RD, RL, Data);
1470 Fields.finishAndAddTo(Parent);
1471}
1472
Alexey Bataev50b3c952016-02-19 10:38:26 +00001473Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001474 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataevceeaa482018-11-21 21:04:34 +00001475 unsigned Reserved2Flags = getDefaultLocationReserved2Flags();
1476 FlagsTy FlagsKey(Flags, Reserved2Flags);
1477 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(FlagsKey);
Alexey Bataev9959db52014-05-06 10:08:46 +00001478 if (!Entry) {
1479 if (!DefaultOpenMPPSource) {
1480 // Initialize default location for psource field of ident_t structure of
1481 // all ident_t objects. Format is ";file;function;line;column;;".
1482 // Taken from
James Y Knight5d71fc52019-01-29 16:37:27 +00001483 // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp_str.cpp
Alexey Bataev9959db52014-05-06 10:08:46 +00001484 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001485 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001486 DefaultOpenMPPSource =
1487 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1488 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001489
Alexey Bataevceeaa482018-11-21 21:04:34 +00001490 llvm::Constant *Data[] = {
1491 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1492 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1493 llvm::ConstantInt::get(CGM.Int32Ty, Reserved2Flags),
1494 llvm::ConstantInt::getNullValue(CGM.Int32Ty), DefaultOpenMPPSource};
Mike Ricee1ca7b62018-08-29 15:45:11 +00001495 llvm::GlobalValue *DefaultOpenMPLocation =
Alexey Bataevceeaa482018-11-21 21:04:34 +00001496 createGlobalStruct(CGM, IdentQTy, isDefaultLocationConstant(), Data, "",
Mike Ricee1ca7b62018-08-29 15:45:11 +00001497 llvm::GlobalValue::PrivateLinkage);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001498 DefaultOpenMPLocation->setUnnamedAddr(
1499 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001500
Alexey Bataevceeaa482018-11-21 21:04:34 +00001501 OpenMPDefaultLocMap[FlagsKey] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001502 }
John McCall7f416cc2015-09-08 08:05:57 +00001503 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001504}
1505
Alexey Bataevfd006c42018-10-05 15:08:53 +00001506void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
1507 bool AtCurrentPoint) {
1508 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1509 assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
1510
1511 llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1512 if (AtCurrentPoint) {
1513 Elem.second.ServiceInsertPt = new llvm::BitCastInst(
1514 Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
1515 } else {
1516 Elem.second.ServiceInsertPt =
1517 new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1518 Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
1519 }
1520}
1521
1522void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
1523 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1524 if (Elem.second.ServiceInsertPt) {
1525 llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
1526 Elem.second.ServiceInsertPt = nullptr;
1527 Ptr->eraseFromParent();
1528 }
1529}
1530
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001531llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1532 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001533 unsigned Flags) {
1534 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001535 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001536 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001537 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001538 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001539
1540 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1541
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001542 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001543 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001544 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1545 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001546 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001547
Alexander Musmanc6388682014-12-15 07:07:06 +00001548 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1549 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001550 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001551 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001552 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001553 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001554 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001555 LocValue = AI;
1556
Alexey Bataevfd006c42018-10-05 15:08:53 +00001557 if (!Elem.second.ServiceInsertPt)
1558 setLocThreadIdInsertPt(CGF);
Alexey Bataev9959db52014-05-06 10:08:46 +00001559 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001560 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001561 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001562 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001563 }
1564
1565 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001566 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1567 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1568 LValue PSource =
1569 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001570
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001571 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001572 if (OMPDebugLoc == nullptr) {
1573 SmallString<128> Buffer2;
1574 llvm::raw_svector_ostream OS2(Buffer2);
1575 // Build debug location
1576 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1577 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001578 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001579 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001580 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1581 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1582 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001583 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001584 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001585 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001586
John McCall7f416cc2015-09-08 08:05:57 +00001587 // Our callers always pass this to a runtime function, so for
1588 // convenience, go ahead and return a naked pointer.
1589 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001590}
1591
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001592llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1593 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001594 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1595
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001596 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001597 // Check whether we've already cached a load of the thread id in this
1598 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001599 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001600 if (I != OpenMPLocThreadIDMap.end()) {
1601 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001602 if (ThreadID != nullptr)
1603 return ThreadID;
1604 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001605 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001606 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1607 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001608 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001609 if (auto *OMPRegionInfo =
1610 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1611 if (OMPRegionInfo->getThreadIDVariable()) {
1612 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001613 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001614 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001615 // If value loaded in entry block, cache it and use it everywhere in
1616 // function.
1617 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1618 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1619 Elem.second.ThreadID = ThreadID;
1620 }
1621 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001622 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001623 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001624 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001625
1626 // This is not an outlined function region - need to call __kmpc_int32
1627 // kmpc_global_thread_num(ident_t *loc).
1628 // Generate thread id value and cache this value for use across the
1629 // function.
Alexey Bataevfd006c42018-10-05 15:08:53 +00001630 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1631 if (!Elem.second.ServiceInsertPt)
1632 setLocThreadIdInsertPt(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001633 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001634 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001635 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001636 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1637 emitUpdateLocation(CGF, Loc));
1638 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001639 Elem.second.ThreadID = Call;
1640 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001641}
1642
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001643void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001644 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataevfd006c42018-10-05 15:08:53 +00001645 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1646 clearLocThreadIdInsertPt(CGF);
Alexey Bataev03b340a2014-10-21 03:16:40 +00001647 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001648 }
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001649 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001650 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001651 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001652 FunctionUDRMap.erase(CGF.CurFn);
1653 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001654}
1655
1656llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001657 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001658}
1659
1660llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001661 if (!Kmpc_MicroTy) {
1662 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1663 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1664 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1665 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1666 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001667 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1668}
1669
James Y Knight9871db02019-02-05 16:42:33 +00001670llvm::FunctionCallee CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
1671 llvm::FunctionCallee RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001672 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001673 case OMPRTL__kmpc_fork_call: {
1674 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1675 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001676 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1677 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001678 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001679 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001680 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
James Y Knight9871db02019-02-05 16:42:33 +00001681 if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
Johannes Doerfertac991bb2019-01-19 05:36:54 +00001682 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
1683 llvm::LLVMContext &Ctx = F->getContext();
1684 llvm::MDBuilder MDB(Ctx);
1685 // Annotate the callback behavior of the __kmpc_fork_call:
1686 // - The callback callee is argument number 2 (microtask).
1687 // - The first two arguments of the callback callee are unknown (-1).
1688 // - All variadic arguments to the __kmpc_fork_call are passed to the
1689 // callback callee.
1690 F->addMetadata(
1691 llvm::LLVMContext::MD_callback,
1692 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1693 2, {-1, -1},
1694 /* VarArgsArePassed */ true)}));
1695 }
1696 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001697 break;
1698 }
1699 case OMPRTL__kmpc_global_thread_num: {
1700 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001701 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001702 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001703 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001704 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1705 break;
1706 }
Alexey Bataev97720002014-11-11 04:05:39 +00001707 case OMPRTL__kmpc_threadprivate_cached: {
1708 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1709 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1710 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1711 CGM.VoidPtrTy, CGM.SizeTy,
1712 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001713 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001714 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1715 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1716 break;
1717 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001718 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001719 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1720 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001721 llvm::Type *TypeParams[] = {
1722 getIdentTyPointerTy(), CGM.Int32Ty,
1723 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001724 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001725 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1726 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1727 break;
1728 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001729 case OMPRTL__kmpc_critical_with_hint: {
1730 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1731 // kmp_critical_name *crit, uintptr_t hint);
1732 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1733 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1734 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001735 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001736 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1737 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1738 break;
1739 }
Alexey Bataev97720002014-11-11 04:05:39 +00001740 case OMPRTL__kmpc_threadprivate_register: {
1741 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1742 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1743 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001744 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001745 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1746 /*isVarArg*/ false)->getPointerTo();
1747 // typedef void *(*kmpc_cctor)(void *, void *);
1748 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001749 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001750 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001751 /*isVarArg*/ false)
1752 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001753 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001754 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001755 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1756 ->getPointerTo();
1757 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1758 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001759 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001760 /*isVarArg*/ false);
1761 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1762 break;
1763 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001764 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001765 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1766 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001767 llvm::Type *TypeParams[] = {
1768 getIdentTyPointerTy(), CGM.Int32Ty,
1769 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001770 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001771 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1772 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1773 break;
1774 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001775 case OMPRTL__kmpc_cancel_barrier: {
1776 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1777 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001778 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001779 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001780 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1781 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001782 break;
1783 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001784 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001785 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001786 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001787 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001788 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1789 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1790 break;
1791 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001792 case OMPRTL__kmpc_for_static_fini: {
1793 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1794 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001795 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001796 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1797 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1798 break;
1799 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001800 case OMPRTL__kmpc_push_num_threads: {
1801 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1802 // kmp_int32 num_threads)
1803 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1804 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001805 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001806 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1807 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1808 break;
1809 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001810 case OMPRTL__kmpc_serialized_parallel: {
1811 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1812 // global_tid);
1813 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001814 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001815 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1816 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1817 break;
1818 }
1819 case OMPRTL__kmpc_end_serialized_parallel: {
1820 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1821 // global_tid);
1822 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001823 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001824 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1825 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1826 break;
1827 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001828 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001829 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001830 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001831 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001832 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001833 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1834 break;
1835 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001836 case OMPRTL__kmpc_master: {
1837 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1838 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001839 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001840 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1841 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1842 break;
1843 }
1844 case OMPRTL__kmpc_end_master: {
1845 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1846 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001847 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001848 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1849 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1850 break;
1851 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001852 case OMPRTL__kmpc_omp_taskyield: {
1853 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1854 // int end_part);
1855 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001856 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001857 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1858 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1859 break;
1860 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001861 case OMPRTL__kmpc_single: {
1862 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1863 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001864 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001865 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1866 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1867 break;
1868 }
1869 case OMPRTL__kmpc_end_single: {
1870 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1871 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001872 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001873 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1874 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1875 break;
1876 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001877 case OMPRTL__kmpc_omp_task_alloc: {
1878 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1879 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1880 // kmp_routine_entry_t *task_entry);
1881 assert(KmpRoutineEntryPtrTy != nullptr &&
1882 "Type kmp_routine_entry_t must be created.");
1883 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1884 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1885 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001886 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001887 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1888 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1889 break;
1890 }
1891 case OMPRTL__kmpc_omp_task: {
1892 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1893 // *new_task);
1894 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1895 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001896 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001897 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1898 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1899 break;
1900 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001901 case OMPRTL__kmpc_copyprivate: {
1902 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001903 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001904 // kmp_int32 didit);
1905 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1906 auto *CpyFnTy =
1907 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001908 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001909 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1910 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001911 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001912 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1913 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1914 break;
1915 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001916 case OMPRTL__kmpc_reduce: {
1917 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1918 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1919 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1920 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1921 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1922 /*isVarArg=*/false);
1923 llvm::Type *TypeParams[] = {
1924 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1925 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1926 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001927 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001928 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1929 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1930 break;
1931 }
1932 case OMPRTL__kmpc_reduce_nowait: {
1933 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1934 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1935 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1936 // *lck);
1937 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1938 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1939 /*isVarArg=*/false);
1940 llvm::Type *TypeParams[] = {
1941 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1942 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1943 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001944 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001945 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1946 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1947 break;
1948 }
1949 case OMPRTL__kmpc_end_reduce: {
1950 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1951 // kmp_critical_name *lck);
1952 llvm::Type *TypeParams[] = {
1953 getIdentTyPointerTy(), CGM.Int32Ty,
1954 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001955 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001956 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1957 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1958 break;
1959 }
1960 case OMPRTL__kmpc_end_reduce_nowait: {
1961 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1962 // kmp_critical_name *lck);
1963 llvm::Type *TypeParams[] = {
1964 getIdentTyPointerTy(), CGM.Int32Ty,
1965 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001966 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001967 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1968 RTLFn =
1969 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1970 break;
1971 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001972 case OMPRTL__kmpc_omp_task_begin_if0: {
1973 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1974 // *new_task);
1975 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1976 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001977 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001978 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1979 RTLFn =
1980 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1981 break;
1982 }
1983 case OMPRTL__kmpc_omp_task_complete_if0: {
1984 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1985 // *new_task);
1986 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1987 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001988 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001989 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1990 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1991 /*Name=*/"__kmpc_omp_task_complete_if0");
1992 break;
1993 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001994 case OMPRTL__kmpc_ordered: {
1995 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1996 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001997 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001998 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1999 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
2000 break;
2001 }
2002 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002003 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002004 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002005 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002006 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2007 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
2008 break;
2009 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002010 case OMPRTL__kmpc_omp_taskwait: {
2011 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
2012 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002013 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002014 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2015 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
2016 break;
2017 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002018 case OMPRTL__kmpc_taskgroup: {
2019 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
2020 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002021 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002022 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2023 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
2024 break;
2025 }
2026 case OMPRTL__kmpc_end_taskgroup: {
2027 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
2028 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002029 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002030 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2031 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
2032 break;
2033 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00002034 case OMPRTL__kmpc_push_proc_bind: {
2035 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
2036 // int proc_bind)
2037 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002038 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002039 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2040 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2041 break;
2042 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002043 case OMPRTL__kmpc_omp_task_with_deps: {
2044 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2045 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2046 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2047 llvm::Type *TypeParams[] = {
2048 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2049 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002050 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002051 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2052 RTLFn =
2053 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2054 break;
2055 }
2056 case OMPRTL__kmpc_omp_wait_deps: {
2057 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2058 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2059 // kmp_depend_info_t *noalias_dep_list);
2060 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2061 CGM.Int32Ty, CGM.VoidPtrTy,
2062 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002063 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002064 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2065 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2066 break;
2067 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002068 case OMPRTL__kmpc_cancellationpoint: {
2069 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2070 // global_tid, kmp_int32 cncl_kind)
2071 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002072 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002073 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2074 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2075 break;
2076 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002077 case OMPRTL__kmpc_cancel: {
2078 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2079 // kmp_int32 cncl_kind)
2080 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002081 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002082 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2083 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2084 break;
2085 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002086 case OMPRTL__kmpc_push_num_teams: {
2087 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2088 // kmp_int32 num_teams, kmp_int32 num_threads)
2089 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2090 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002091 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002092 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2093 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2094 break;
2095 }
2096 case OMPRTL__kmpc_fork_teams: {
2097 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2098 // microtask, ...);
2099 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2100 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002101 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002102 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2103 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
James Y Knight9871db02019-02-05 16:42:33 +00002104 if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002105 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
2106 llvm::LLVMContext &Ctx = F->getContext();
2107 llvm::MDBuilder MDB(Ctx);
2108 // Annotate the callback behavior of the __kmpc_fork_teams:
2109 // - The callback callee is argument number 2 (microtask).
2110 // - The first two arguments of the callback callee are unknown (-1).
2111 // - All variadic arguments to the __kmpc_fork_teams are passed to the
2112 // callback callee.
2113 F->addMetadata(
2114 llvm::LLVMContext::MD_callback,
2115 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2116 2, {-1, -1},
2117 /* VarArgsArePassed */ true)}));
2118 }
2119 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002120 break;
2121 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002122 case OMPRTL__kmpc_taskloop: {
2123 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2124 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2125 // sched, kmp_uint64 grainsize, void *task_dup);
2126 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2127 CGM.IntTy,
2128 CGM.VoidPtrTy,
2129 CGM.IntTy,
2130 CGM.Int64Ty->getPointerTo(),
2131 CGM.Int64Ty->getPointerTo(),
2132 CGM.Int64Ty,
2133 CGM.IntTy,
2134 CGM.IntTy,
2135 CGM.Int64Ty,
2136 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002137 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002138 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2139 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2140 break;
2141 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002142 case OMPRTL__kmpc_doacross_init: {
2143 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2144 // num_dims, struct kmp_dim *dims);
2145 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2146 CGM.Int32Ty,
2147 CGM.Int32Ty,
2148 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002149 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002150 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2151 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2152 break;
2153 }
2154 case OMPRTL__kmpc_doacross_fini: {
2155 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2156 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002157 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002158 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2159 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2160 break;
2161 }
2162 case OMPRTL__kmpc_doacross_post: {
2163 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2164 // *vec);
2165 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2166 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002167 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002168 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2169 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2170 break;
2171 }
2172 case OMPRTL__kmpc_doacross_wait: {
2173 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2174 // *vec);
2175 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2176 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002177 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002178 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2179 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2180 break;
2181 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002182 case OMPRTL__kmpc_task_reduction_init: {
2183 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2184 // *data);
2185 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002186 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002187 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2188 RTLFn =
2189 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2190 break;
2191 }
2192 case OMPRTL__kmpc_task_reduction_get_th_data: {
2193 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2194 // *d);
2195 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002196 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002197 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2198 RTLFn = CGM.CreateRuntimeFunction(
2199 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2200 break;
2201 }
Alexey Bataev4f680db2019-03-19 16:41:16 +00002202 case OMPRTL__kmpc_alloc: {
2203 // Build to void *__kmpc_alloc(int gtid, size_t sz, const omp_allocator_t
2204 // *al);
2205 // omp_allocator_t type is void *.
2206 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.SizeTy, CGM.VoidPtrPtrTy};
2207 auto *FnTy =
2208 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2209 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_alloc");
2210 break;
2211 }
2212 case OMPRTL__kmpc_free: {
2213 // Build to void __kmpc_free(int gtid, void *ptr, const omp_allocator_t
2214 // *al);
2215 // omp_allocator_t type is void *.
2216 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrPtrTy};
2217 auto *FnTy =
2218 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2219 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_free");
2220 break;
2221 }
Alexey Bataev7bb33532019-01-07 21:30:43 +00002222 case OMPRTL__kmpc_push_target_tripcount: {
2223 // Build void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
2224 // size);
2225 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int64Ty};
2226 llvm::FunctionType *FnTy =
2227 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2228 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_target_tripcount");
2229 break;
2230 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002231 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002232 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2233 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002234 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002235 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002236 CGM.VoidPtrTy,
2237 CGM.Int32Ty,
2238 CGM.VoidPtrPtrTy,
2239 CGM.VoidPtrPtrTy,
2240 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002241 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002242 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002243 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2244 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2245 break;
2246 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002247 case OMPRTL__tgt_target_nowait: {
2248 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2249 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2250 // int64_t *arg_types);
2251 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2252 CGM.VoidPtrTy,
2253 CGM.Int32Ty,
2254 CGM.VoidPtrPtrTy,
2255 CGM.VoidPtrPtrTy,
2256 CGM.SizeTy->getPointerTo(),
2257 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002258 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002259 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2260 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2261 break;
2262 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002263 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002264 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002265 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002266 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2267 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002268 CGM.VoidPtrTy,
2269 CGM.Int32Ty,
2270 CGM.VoidPtrPtrTy,
2271 CGM.VoidPtrPtrTy,
2272 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002273 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002274 CGM.Int32Ty,
2275 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002276 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002277 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2278 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2279 break;
2280 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002281 case OMPRTL__tgt_target_teams_nowait: {
2282 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2283 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2284 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2285 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2286 CGM.VoidPtrTy,
2287 CGM.Int32Ty,
2288 CGM.VoidPtrPtrTy,
2289 CGM.VoidPtrPtrTy,
2290 CGM.SizeTy->getPointerTo(),
2291 CGM.Int64Ty->getPointerTo(),
2292 CGM.Int32Ty,
2293 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002294 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002295 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2296 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2297 break;
2298 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002299 case OMPRTL__tgt_register_lib: {
2300 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2301 QualType ParamTy =
2302 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2303 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002304 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002305 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2306 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2307 break;
2308 }
2309 case OMPRTL__tgt_unregister_lib: {
2310 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2311 QualType ParamTy =
2312 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2313 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002314 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002315 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2316 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2317 break;
2318 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002319 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002320 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2321 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2322 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002323 CGM.Int32Ty,
2324 CGM.VoidPtrPtrTy,
2325 CGM.VoidPtrPtrTy,
2326 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002327 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002328 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002329 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2330 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2331 break;
2332 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002333 case OMPRTL__tgt_target_data_begin_nowait: {
2334 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2335 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2336 // *arg_types);
2337 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2338 CGM.Int32Ty,
2339 CGM.VoidPtrPtrTy,
2340 CGM.VoidPtrPtrTy,
2341 CGM.SizeTy->getPointerTo(),
2342 CGM.Int64Ty->getPointerTo()};
2343 auto *FnTy =
2344 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2345 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2346 break;
2347 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002348 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002349 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2350 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2351 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002352 CGM.Int32Ty,
2353 CGM.VoidPtrPtrTy,
2354 CGM.VoidPtrPtrTy,
2355 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002356 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002357 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002358 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2359 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2360 break;
2361 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002362 case OMPRTL__tgt_target_data_end_nowait: {
2363 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2364 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2365 // *arg_types);
2366 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2367 CGM.Int32Ty,
2368 CGM.VoidPtrPtrTy,
2369 CGM.VoidPtrPtrTy,
2370 CGM.SizeTy->getPointerTo(),
2371 CGM.Int64Ty->getPointerTo()};
2372 auto *FnTy =
2373 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2374 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2375 break;
2376 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002377 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002378 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2379 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2380 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002381 CGM.Int32Ty,
2382 CGM.VoidPtrPtrTy,
2383 CGM.VoidPtrPtrTy,
2384 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002385 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002386 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002387 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2388 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2389 break;
2390 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002391 case OMPRTL__tgt_target_data_update_nowait: {
2392 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2393 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2394 // *arg_types);
2395 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2396 CGM.Int32Ty,
2397 CGM.VoidPtrPtrTy,
2398 CGM.VoidPtrPtrTy,
2399 CGM.SizeTy->getPointerTo(),
2400 CGM.Int64Ty->getPointerTo()};
2401 auto *FnTy =
2402 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2403 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2404 break;
2405 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002406 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002407 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002408 return RTLFn;
2409}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002410
James Y Knight9871db02019-02-05 16:42:33 +00002411llvm::FunctionCallee
2412CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, bool IVSigned) {
Alexander Musman21212e42015-03-13 10:38:23 +00002413 assert((IVSize == 32 || IVSize == 64) &&
2414 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002415 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2416 : "__kmpc_for_static_init_4u")
2417 : (IVSigned ? "__kmpc_for_static_init_8"
2418 : "__kmpc_for_static_init_8u");
2419 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2420 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002421 llvm::Type *TypeParams[] = {
2422 getIdentTyPointerTy(), // loc
2423 CGM.Int32Ty, // tid
2424 CGM.Int32Ty, // schedtype
2425 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2426 PtrTy, // p_lower
2427 PtrTy, // p_upper
2428 PtrTy, // p_stride
2429 ITy, // incr
2430 ITy // chunk
2431 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002432 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002433 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2434 return CGM.CreateRuntimeFunction(FnTy, Name);
2435}
2436
James Y Knight9871db02019-02-05 16:42:33 +00002437llvm::FunctionCallee
2438CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002439 assert((IVSize == 32 || IVSize == 64) &&
2440 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002441 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002442 IVSize == 32
2443 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2444 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002445 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002446 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2447 CGM.Int32Ty, // tid
2448 CGM.Int32Ty, // schedtype
2449 ITy, // lower
2450 ITy, // upper
2451 ITy, // stride
2452 ITy // chunk
2453 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002454 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002455 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2456 return CGM.CreateRuntimeFunction(FnTy, Name);
2457}
2458
James Y Knight9871db02019-02-05 16:42:33 +00002459llvm::FunctionCallee
2460CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002461 assert((IVSize == 32 || IVSize == 64) &&
2462 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002463 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002464 IVSize == 32
2465 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2466 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2467 llvm::Type *TypeParams[] = {
2468 getIdentTyPointerTy(), // loc
2469 CGM.Int32Ty, // tid
2470 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002471 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002472 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2473 return CGM.CreateRuntimeFunction(FnTy, Name);
2474}
2475
James Y Knight9871db02019-02-05 16:42:33 +00002476llvm::FunctionCallee
2477CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002478 assert((IVSize == 32 || IVSize == 64) &&
2479 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002480 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002481 IVSize == 32
2482 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2483 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002484 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2485 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002486 llvm::Type *TypeParams[] = {
2487 getIdentTyPointerTy(), // loc
2488 CGM.Int32Ty, // tid
2489 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2490 PtrTy, // p_lower
2491 PtrTy, // p_upper
2492 PtrTy // p_stride
2493 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002494 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002495 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2496 return CGM.CreateRuntimeFunction(FnTy, Name);
2497}
2498
Alexey Bataev03f270c2018-03-30 18:31:07 +00002499Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2500 if (CGM.getLangOpts().OpenMPSimd)
2501 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002502 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002503 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002504 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2505 SmallString<64> PtrName;
2506 {
2507 llvm::raw_svector_ostream OS(PtrName);
2508 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2509 }
2510 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2511 if (!Ptr) {
2512 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2513 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2514 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002515 if (!CGM.getLangOpts().OpenMPIsDevice) {
2516 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2517 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2518 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2519 }
2520 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2521 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002522 }
2523 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2524 }
2525 return Address::invalid();
2526}
2527
Alexey Bataev97720002014-11-11 04:05:39 +00002528llvm::Constant *
2529CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002530 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2531 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002532 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002533 std::string Suffix = getName({"cache", ""});
2534 return getOrCreateInternalVariable(
2535 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002536}
2537
John McCall7f416cc2015-09-08 08:05:57 +00002538Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2539 const VarDecl *VD,
2540 Address VDAddr,
2541 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002542 if (CGM.getLangOpts().OpenMPUseTLS &&
2543 CGM.getContext().getTargetInfo().isTLSSupported())
2544 return VDAddr;
2545
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002546 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002547 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002548 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2549 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002550 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2551 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002552 return Address(CGF.EmitRuntimeCall(
2553 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2554 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002555}
2556
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002557void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002558 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002559 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2560 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2561 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002562 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002563 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002564 OMPLoc);
2565 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2566 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002567 llvm::Value *Args[] = {
2568 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2569 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002570 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002571 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002572}
2573
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002574llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002575 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002576 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002577 if (CGM.getLangOpts().OpenMPUseTLS &&
2578 CGM.getContext().getTargetInfo().isTLSSupported())
2579 return nullptr;
2580
Alexey Bataev97720002014-11-11 04:05:39 +00002581 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002582 if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
Alexey Bataev97720002014-11-11 04:05:39 +00002583 QualType ASTTy = VD->getType();
2584
2585 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002586 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002587 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2588 // Generate function that re-emits the declaration's initializer into the
2589 // threadprivate copy of the variable VD
2590 CodeGenFunction CtorCGF(CGM);
2591 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002592 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2593 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002594 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002595 Args.push_back(&Dst);
2596
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002597 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002598 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002599 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002600 std::string Name = getName({"__kmpc_global_ctor_", ""});
2601 llvm::Function *Fn =
2602 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002603 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002604 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002605 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002606 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002607 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002608 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002609 Arg = CtorCGF.Builder.CreateElementBitCast(
2610 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002611 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2612 /*IsInitializer=*/true);
2613 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002614 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002615 CGM.getContext().VoidPtrTy, Dst.getLocation());
2616 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2617 CtorCGF.FinishFunction();
2618 Ctor = Fn;
2619 }
2620 if (VD->getType().isDestructedType() != QualType::DK_none) {
2621 // Generate function that emits destructor call for the threadprivate copy
2622 // of the variable VD
2623 CodeGenFunction DtorCGF(CGM);
2624 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002625 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2626 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002627 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002628 Args.push_back(&Dst);
2629
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002630 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002631 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002632 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002633 std::string Name = getName({"__kmpc_global_dtor_", ""});
2634 llvm::Function *Fn =
2635 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002636 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002637 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002638 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002639 // Create a scope with an artificial location for the body of this function.
2640 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002641 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002642 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002643 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2644 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002645 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2646 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2647 DtorCGF.FinishFunction();
2648 Dtor = Fn;
2649 }
2650 // Do not emit init function if it is not required.
2651 if (!Ctor && !Dtor)
2652 return nullptr;
2653
2654 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002655 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2656 /*isVarArg=*/false)
2657 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002658 // Copying constructor for the threadprivate variable.
2659 // Must be NULL - reserved by runtime, but currently it requires that this
2660 // parameter is always NULL. Otherwise it fires assertion.
2661 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2662 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002663 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2664 /*isVarArg=*/false)
2665 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002666 Ctor = llvm::Constant::getNullValue(CtorTy);
2667 }
2668 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002669 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2670 /*isVarArg=*/false)
2671 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002672 Dtor = llvm::Constant::getNullValue(DtorTy);
2673 }
2674 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002675 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002676 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002677 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002678 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002679 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002680 CodeGenFunction InitCGF(CGM);
2681 FunctionArgList ArgList;
2682 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2683 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002684 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002685 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002686 InitCGF.FinishFunction();
2687 return InitFunction;
2688 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002689 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002690 }
2691 return nullptr;
2692}
2693
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002694/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002695/// consists of the file and device IDs as well as line number associated with
2696/// the relevant entry source location.
2697static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2698 unsigned &DeviceID, unsigned &FileID,
2699 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002700 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002701
2702 // The loc should be always valid and have a file ID (the user cannot use
2703 // #pragma directives in macros)
2704
2705 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002706
2707 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2708 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2709
2710 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002711 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2712 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2713 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002714
2715 DeviceID = ID.getDevice();
2716 FileID = ID.getFile();
2717 LineNum = PLoc.getLine();
2718}
2719
2720bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2721 llvm::GlobalVariable *Addr,
2722 bool PerformInit) {
2723 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002724 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002725 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
Alexey Bataevd01b7492018-08-15 19:45:12 +00002726 return CGM.getLangOpts().OpenMPIsDevice;
Alexey Bataev34f8a702018-03-28 14:28:54 +00002727 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002728 if (VD && !DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
Alexey Bataev34f8a702018-03-28 14:28:54 +00002729 return CGM.getLangOpts().OpenMPIsDevice;
2730
2731 QualType ASTTy = VD->getType();
2732
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002733 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002734 // Produce the unique prefix to identify the new target regions. We use
2735 // the source location of the variable declaration which we know to not
2736 // conflict with any target region.
2737 unsigned DeviceID;
2738 unsigned FileID;
2739 unsigned Line;
2740 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2741 SmallString<128> Buffer, Out;
2742 {
2743 llvm::raw_svector_ostream OS(Buffer);
2744 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2745 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2746 }
2747
2748 const Expr *Init = VD->getAnyInitializer();
2749 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2750 llvm::Constant *Ctor;
2751 llvm::Constant *ID;
2752 if (CGM.getLangOpts().OpenMPIsDevice) {
2753 // Generate function that re-emits the declaration's initializer into
2754 // the threadprivate copy of the variable VD
2755 CodeGenFunction CtorCGF(CGM);
2756
2757 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2758 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2759 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2760 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2761 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2762 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2763 FunctionArgList(), Loc, Loc);
2764 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2765 CtorCGF.EmitAnyExprToMem(Init,
2766 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2767 Init->getType().getQualifiers(),
2768 /*IsInitializer=*/true);
2769 CtorCGF.FinishFunction();
2770 Ctor = Fn;
2771 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002772 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002773 } else {
2774 Ctor = new llvm::GlobalVariable(
2775 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2776 llvm::GlobalValue::PrivateLinkage,
2777 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2778 ID = Ctor;
2779 }
2780
2781 // Register the information for the entry associated with the constructor.
2782 Out.clear();
2783 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2784 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002785 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002786 }
2787 if (VD->getType().isDestructedType() != QualType::DK_none) {
2788 llvm::Constant *Dtor;
2789 llvm::Constant *ID;
2790 if (CGM.getLangOpts().OpenMPIsDevice) {
2791 // Generate function that emits destructor call for the threadprivate
2792 // copy of the variable VD
2793 CodeGenFunction DtorCGF(CGM);
2794
2795 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2796 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2797 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2798 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2799 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2800 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2801 FunctionArgList(), Loc, Loc);
2802 // Create a scope with an artificial location for the body of this
2803 // function.
2804 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2805 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2806 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2807 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2808 DtorCGF.FinishFunction();
2809 Dtor = Fn;
2810 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002811 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002812 } else {
2813 Dtor = new llvm::GlobalVariable(
2814 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2815 llvm::GlobalValue::PrivateLinkage,
2816 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2817 ID = Dtor;
2818 }
2819 // Register the information for the entry associated with the destructor.
2820 Out.clear();
2821 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2822 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002823 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002824 }
2825 return CGM.getLangOpts().OpenMPIsDevice;
2826}
2827
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002828Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2829 QualType VarType,
2830 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002831 std::string Suffix = getName({"artificial", ""});
2832 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002833 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002834 llvm::Value *GAddr =
2835 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002836 llvm::Value *Args[] = {
2837 emitUpdateLocation(CGF, SourceLocation()),
2838 getThreadID(CGF, SourceLocation()),
2839 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2840 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2841 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002842 getOrCreateInternalVariable(
2843 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002844 return Address(
2845 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2846 CGF.EmitRuntimeCall(
2847 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2848 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2849 CGM.getPointerAlign());
2850}
2851
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002852void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2853 const RegionCodeGenTy &ThenGen,
2854 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002855 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2856
2857 // If the condition constant folds and can be elided, try to avoid emitting
2858 // the condition and the dead arm of the if/else.
2859 bool CondConstant;
2860 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002861 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002862 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002863 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002864 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002865 return;
2866 }
2867
2868 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2869 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002870 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2871 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2872 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002873 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2874
2875 // Emit the 'then' code.
2876 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002877 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002878 CGF.EmitBranch(ContBlock);
2879 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002880 // There is no need to emit line number for unconditional branch.
2881 (void)ApplyDebugLocation::CreateEmpty(CGF);
2882 CGF.EmitBlock(ElseBlock);
2883 ElseGen(CGF);
2884 // There is no need to emit line number for unconditional branch.
2885 (void)ApplyDebugLocation::CreateEmpty(CGF);
2886 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002887 // Emit the continuation block for code after the if.
2888 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002889}
2890
Alexey Bataev1d677132015-04-22 13:57:31 +00002891void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002892 llvm::Function *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002893 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002894 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002895 if (!CGF.HaveInsertPoint())
2896 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002897 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002898 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2899 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002900 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002901 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002902 llvm::Value *Args[] = {
2903 RTLoc,
2904 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002905 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002906 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2907 RealArgs.append(std::begin(Args), std::end(Args));
2908 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2909
James Y Knight9871db02019-02-05 16:42:33 +00002910 llvm::FunctionCallee RTLFn =
2911 RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002912 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2913 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002914 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2915 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002916 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2917 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002918 // Build calls:
2919 // __kmpc_serialized_parallel(&Loc, GTid);
2920 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002921 CGF.EmitRuntimeCall(
2922 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002923
Alexey Bataev1d677132015-04-22 13:57:31 +00002924 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002925 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2926 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002927 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002928 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataev8521ff62018-07-25 20:03:01 +00002929 // ThreadId for serialized parallels is 0.
2930 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002931 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2932 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002933 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002934
Alexey Bataev1d677132015-04-22 13:57:31 +00002935 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002936 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002937 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002938 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2939 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002940 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002941 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002942 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002943 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002944 RegionCodeGenTy ThenRCG(ThenGen);
2945 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002946 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002947}
2948
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002949// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002950// thread-ID variable (it is passed in a first argument of the outlined function
2951// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2952// regular serial code region, get thread ID by calling kmp_int32
2953// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2954// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002955Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2956 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002957 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002958 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002959 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002960 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002961
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002962 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2963 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002964 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002965 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002966 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002967 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002968
2969 return ThreadIDTemp;
2970}
2971
Alexey Bataev1af5bd52019-03-05 17:47:18 +00002972llvm::Constant *CGOpenMPRuntime::getOrCreateInternalVariable(
2973 llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002974 SmallString<256> Buffer;
2975 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002976 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002977 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002978 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002979 if (Elem.second) {
2980 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002981 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002982 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002983 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002984
David Blaikie13156b62014-11-19 03:06:06 +00002985 return Elem.second = new llvm::GlobalVariable(
2986 CGM.getModule(), Ty, /*IsConstant*/ false,
2987 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
Alexey Bataev1af5bd52019-03-05 17:47:18 +00002988 Elem.first(), /*InsertBefore=*/nullptr,
2989 llvm::GlobalValue::NotThreadLocal, AddressSpace);
Alexey Bataev97720002014-11-11 04:05:39 +00002990}
2991
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002992llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002993 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2994 std::string Name = getName({Prefix, "var"});
2995 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002996}
2997
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002998namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002999/// Common pre(post)-action for different OpenMP constructs.
3000class CommonActionTy final : public PrePostActionTy {
James Y Knight9871db02019-02-05 16:42:33 +00003001 llvm::FunctionCallee EnterCallee;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003002 ArrayRef<llvm::Value *> EnterArgs;
James Y Knight9871db02019-02-05 16:42:33 +00003003 llvm::FunctionCallee ExitCallee;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003004 ArrayRef<llvm::Value *> ExitArgs;
3005 bool Conditional;
3006 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003007
3008public:
James Y Knight9871db02019-02-05 16:42:33 +00003009 CommonActionTy(llvm::FunctionCallee EnterCallee,
3010 ArrayRef<llvm::Value *> EnterArgs,
3011 llvm::FunctionCallee ExitCallee,
3012 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003013 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
3014 ExitArgs(ExitArgs), Conditional(Conditional) {}
3015 void Enter(CodeGenFunction &CGF) override {
3016 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
3017 if (Conditional) {
3018 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
3019 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
3020 ContBlock = CGF.createBasicBlock("omp_if.end");
3021 // Generate the branch (If-stmt)
3022 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
3023 CGF.EmitBlock(ThenBlock);
3024 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00003025 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003026 void Done(CodeGenFunction &CGF) {
3027 // Emit the rest of blocks/branches
3028 CGF.EmitBranch(ContBlock);
3029 CGF.EmitBlock(ContBlock, true);
3030 }
3031 void Exit(CodeGenFunction &CGF) override {
3032 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00003033 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003034};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003035} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003036
3037void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
3038 StringRef CriticalName,
3039 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00003040 SourceLocation Loc, const Expr *Hint) {
3041 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00003042 // CriticalOpGen();
3043 // __kmpc_end_critical(ident_t *, gtid, Lock);
3044 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00003045 if (!CGF.HaveInsertPoint())
3046 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00003047 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3048 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003049 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
3050 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00003051 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003052 EnterArgs.push_back(CGF.Builder.CreateIntCast(
3053 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
3054 }
3055 CommonActionTy Action(
3056 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
3057 : OMPRTL__kmpc_critical),
3058 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
3059 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00003060 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00003061}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003062
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003063void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003064 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003065 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003066 if (!CGF.HaveInsertPoint())
3067 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00003068 // if(__kmpc_master(ident_t *, gtid)) {
3069 // MasterOpGen();
3070 // __kmpc_end_master(ident_t *, gtid);
3071 // }
3072 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003073 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003074 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
3075 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
3076 /*Conditional=*/true);
3077 MasterOpGen.setAction(Action);
3078 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
3079 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00003080}
3081
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003082void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
3083 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003084 if (!CGF.HaveInsertPoint())
3085 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003086 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3087 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003088 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003089 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003090 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003091 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3092 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003093}
3094
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003095void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3096 const RegionCodeGenTy &TaskgroupOpGen,
3097 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003098 if (!CGF.HaveInsertPoint())
3099 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003100 // __kmpc_taskgroup(ident_t *, gtid);
3101 // TaskgroupOpGen();
3102 // __kmpc_end_taskgroup(ident_t *, gtid);
3103 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003104 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3105 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3106 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3107 Args);
3108 TaskgroupOpGen.setAction(Action);
3109 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003110}
3111
John McCall7f416cc2015-09-08 08:05:57 +00003112/// Given an array of pointers to variables, project the address of a
3113/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003114static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3115 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003116 // Pull out the pointer to the variable.
James Y Knight751fe282019-02-09 22:22:28 +00003117 Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index);
John McCall7f416cc2015-09-08 08:05:57 +00003118 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3119
3120 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003121 Addr = CGF.Builder.CreateElementBitCast(
3122 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003123 return Addr;
3124}
3125
Alexey Bataeva63048e2015-03-23 06:18:07 +00003126static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003127 CodeGenModule &CGM, llvm::Type *ArgsType,
3128 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003129 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3130 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003131 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003132 // void copy_func(void *LHSArg, void *RHSArg);
3133 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003134 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3135 ImplicitParamDecl::Other);
3136 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3137 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003138 Args.push_back(&LHSArg);
3139 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003140 const auto &CGFI =
3141 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003142 std::string Name =
3143 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3144 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3145 llvm::GlobalValue::InternalLinkage, Name,
3146 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003147 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003148 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003149 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003150 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003151 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003152 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003153 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3154 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3155 ArgsType), CGF.getPointerAlign());
3156 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3157 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3158 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003159 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3160 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3161 // ...
3162 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003163 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003164 const auto *DestVar =
3165 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003166 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3167
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003168 const auto *SrcVar =
3169 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003170 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3171
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003172 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003173 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003174 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003175 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003176 CGF.FinishFunction();
3177 return Fn;
3178}
3179
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003180void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003181 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003182 SourceLocation Loc,
3183 ArrayRef<const Expr *> CopyprivateVars,
3184 ArrayRef<const Expr *> SrcExprs,
3185 ArrayRef<const Expr *> DstExprs,
3186 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003187 if (!CGF.HaveInsertPoint())
3188 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003189 assert(CopyprivateVars.size() == SrcExprs.size() &&
3190 CopyprivateVars.size() == DstExprs.size() &&
3191 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003192 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003193 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003194 // if(__kmpc_single(ident_t *, gtid)) {
3195 // SingleOpGen();
3196 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003197 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003198 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003199 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3200 // <copy_func>, did_it);
3201
John McCall7f416cc2015-09-08 08:05:57 +00003202 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003203 if (!CopyprivateVars.empty()) {
3204 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003205 QualType KmpInt32Ty =
3206 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003207 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003208 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003209 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003210 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003211 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003212 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3213 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3214 /*Conditional=*/true);
3215 SingleOpGen.setAction(Action);
3216 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3217 if (DidIt.isValid()) {
3218 // did_it = 1;
3219 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3220 }
3221 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003222 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3223 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003224 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003225 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003226 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003227 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3228 /*IndexTypeQuals=*/0);
3229 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003230 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003231 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3232 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
James Y Knight751fe282019-02-09 22:22:28 +00003233 Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I);
John McCall7f416cc2015-09-08 08:05:57 +00003234 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003235 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003236 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3237 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003238 }
3239 // Build function that copies private values from single region to all other
3240 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003241 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003242 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003243 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003244 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003245 Address CL =
3246 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3247 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003248 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003249 llvm::Value *Args[] = {
3250 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3251 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003252 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003253 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003254 CpyFn, // void (*) (void *, void *) <copy_func>
3255 DidItVal // i32 did_it
3256 };
3257 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3258 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003259}
3260
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003261void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3262 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003263 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003264 if (!CGF.HaveInsertPoint())
3265 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003266 // __kmpc_ordered(ident_t *, gtid);
3267 // OrderedOpGen();
3268 // __kmpc_end_ordered(ident_t *, gtid);
3269 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003270 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003271 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003272 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3273 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3274 Args);
3275 OrderedOpGen.setAction(Action);
3276 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3277 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003278 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003279 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003280}
3281
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003282unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003283 unsigned Flags;
3284 if (Kind == OMPD_for)
3285 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3286 else if (Kind == OMPD_sections)
3287 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3288 else if (Kind == OMPD_single)
3289 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3290 else if (Kind == OMPD_barrier)
3291 Flags = OMP_IDENT_BARRIER_EXPL;
3292 else
3293 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003294 return Flags;
3295}
3296
Alexey Bataevf6a53d62019-03-18 18:40:00 +00003297void CGOpenMPRuntime::getDefaultScheduleAndChunk(
3298 CodeGenFunction &CGF, const OMPLoopDirective &S,
3299 OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const {
3300 // Check if the loop directive is actually a doacross loop directive. In this
3301 // case choose static, 1 schedule.
3302 if (llvm::any_of(
3303 S.getClausesOfKind<OMPOrderedClause>(),
3304 [](const OMPOrderedClause *C) { return C->getNumForLoops(); })) {
3305 ScheduleKind = OMPC_SCHEDULE_static;
3306 // Chunk size is 1 in this case.
3307 llvm::APInt ChunkSize(32, 1);
3308 ChunkExpr = IntegerLiteral::Create(
3309 CGF.getContext(), ChunkSize,
3310 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3311 SourceLocation());
3312 }
3313}
3314
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003315void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
3316 OpenMPDirectiveKind Kind, bool EmitChecks,
3317 bool ForceSimpleCall) {
3318 if (!CGF.HaveInsertPoint())
3319 return;
3320 // Build call __kmpc_cancel_barrier(loc, thread_id);
3321 // Build call __kmpc_barrier(loc, thread_id);
3322 unsigned Flags = getDefaultFlagsForBarriers(Kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003323 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3324 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003325 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3326 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003327 if (auto *OMPRegionInfo =
3328 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003329 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003330 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003331 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003332 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003333 // if (__kmpc_cancel_barrier()) {
3334 // exit from construct;
3335 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003336 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3337 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3338 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003339 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3340 CGF.EmitBlock(ExitBB);
3341 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003342 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003343 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003344 CGF.EmitBranchThroughCleanup(CancelDestination);
3345 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3346 }
3347 return;
3348 }
3349 }
3350 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003351}
3352
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003353/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003354static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003355 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003356 switch (ScheduleKind) {
3357 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003358 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3359 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003360 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003361 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003362 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003363 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003364 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003365 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3366 case OMPC_SCHEDULE_auto:
3367 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003368 case OMPC_SCHEDULE_unknown:
3369 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003370 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003371 }
3372 llvm_unreachable("Unexpected runtime schedule");
3373}
3374
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003375/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003376static OpenMPSchedType
3377getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3378 // only static is allowed for dist_schedule
3379 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3380}
3381
Alexander Musmanc6388682014-12-15 07:07:06 +00003382bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3383 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003384 OpenMPSchedType Schedule =
3385 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003386 return Schedule == OMP_sch_static;
3387}
3388
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003389bool CGOpenMPRuntime::isStaticNonchunked(
3390 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003391 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003392 return Schedule == OMP_dist_sch_static;
3393}
3394
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003395bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
3396 bool Chunked) const {
3397 OpenMPSchedType Schedule =
3398 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3399 return Schedule == OMP_sch_static_chunked;
3400}
3401
3402bool CGOpenMPRuntime::isStaticChunked(
3403 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3404 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3405 return Schedule == OMP_dist_sch_static_chunked;
3406}
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003407
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003408bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003409 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003410 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003411 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3412 return Schedule != OMP_sch_static;
3413}
3414
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003415static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3416 OpenMPScheduleClauseModifier M1,
3417 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003418 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003419 switch (M1) {
3420 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003421 Modifier = OMP_sch_modifier_monotonic;
3422 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003423 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003424 Modifier = OMP_sch_modifier_nonmonotonic;
3425 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003426 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003427 if (Schedule == OMP_sch_static_chunked)
3428 Schedule = OMP_sch_static_balanced_chunked;
3429 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003430 case OMPC_SCHEDULE_MODIFIER_last:
3431 case OMPC_SCHEDULE_MODIFIER_unknown:
3432 break;
3433 }
3434 switch (M2) {
3435 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003436 Modifier = OMP_sch_modifier_monotonic;
3437 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003438 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003439 Modifier = OMP_sch_modifier_nonmonotonic;
3440 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003441 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003442 if (Schedule == OMP_sch_static_chunked)
3443 Schedule = OMP_sch_static_balanced_chunked;
3444 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003445 case OMPC_SCHEDULE_MODIFIER_last:
3446 case OMPC_SCHEDULE_MODIFIER_unknown:
3447 break;
3448 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003449 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003450}
3451
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003452void CGOpenMPRuntime::emitForDispatchInit(
3453 CodeGenFunction &CGF, SourceLocation Loc,
3454 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3455 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003456 if (!CGF.HaveInsertPoint())
3457 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003458 OpenMPSchedType Schedule = getRuntimeSchedule(
3459 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003460 assert(Ordered ||
3461 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003462 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3463 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003464 // Call __kmpc_dispatch_init(
3465 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3466 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3467 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003468
John McCall7f416cc2015-09-08 08:05:57 +00003469 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003470 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3471 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003472 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003473 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3474 CGF.Builder.getInt32(addMonoNonMonoModifier(
3475 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003476 DispatchValues.LB, // Lower
3477 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003478 CGF.Builder.getIntN(IVSize, 1), // Stride
3479 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003480 };
3481 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3482}
3483
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003484static void emitForStaticInitCall(
3485 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
James Y Knight9871db02019-02-05 16:42:33 +00003486 llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003487 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003488 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003489 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003490 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003491
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003492 assert(!Values.Ordered);
3493 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3494 Schedule == OMP_sch_static_balanced_chunked ||
3495 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3496 Schedule == OMP_dist_sch_static ||
3497 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003498
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003499 // Call __kmpc_for_static_init(
3500 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3501 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3502 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3503 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3504 llvm::Value *Chunk = Values.Chunk;
3505 if (Chunk == nullptr) {
3506 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3507 Schedule == OMP_dist_sch_static) &&
3508 "expected static non-chunked schedule");
3509 // If the Chunk was not specified in the clause - use default value 1.
3510 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3511 } else {
3512 assert((Schedule == OMP_sch_static_chunked ||
3513 Schedule == OMP_sch_static_balanced_chunked ||
3514 Schedule == OMP_ord_static_chunked ||
3515 Schedule == OMP_dist_sch_static_chunked) &&
3516 "expected static chunked schedule");
3517 }
3518 llvm::Value *Args[] = {
3519 UpdateLocation,
3520 ThreadId,
3521 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3522 M2)), // Schedule type
3523 Values.IL.getPointer(), // &isLastIter
3524 Values.LB.getPointer(), // &LB
3525 Values.UB.getPointer(), // &UB
3526 Values.ST.getPointer(), // &Stride
3527 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3528 Chunk // Chunk
3529 };
3530 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003531}
3532
John McCall7f416cc2015-09-08 08:05:57 +00003533void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3534 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003535 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003536 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003537 const StaticRTInput &Values) {
3538 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3539 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3540 assert(isOpenMPWorksharingDirective(DKind) &&
3541 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003542 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003543 isOpenMPLoopDirective(DKind)
3544 ? OMP_IDENT_WORK_LOOP
3545 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003546 llvm::Value *ThreadId = getThreadID(CGF, Loc);
James Y Knight9871db02019-02-05 16:42:33 +00003547 llvm::FunctionCallee StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003548 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003549 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003550 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003551}
John McCall7f416cc2015-09-08 08:05:57 +00003552
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003553void CGOpenMPRuntime::emitDistributeStaticInit(
3554 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003555 OpenMPDistScheduleClauseKind SchedKind,
3556 const CGOpenMPRuntime::StaticRTInput &Values) {
3557 OpenMPSchedType ScheduleNum =
3558 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003559 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003560 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003561 llvm::Value *ThreadId = getThreadID(CGF, Loc);
James Y Knight9871db02019-02-05 16:42:33 +00003562 llvm::FunctionCallee StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003563 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003564 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3565 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003566 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003567}
3568
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003569void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003570 SourceLocation Loc,
3571 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003572 if (!CGF.HaveInsertPoint())
3573 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003574 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003575 llvm::Value *Args[] = {
3576 emitUpdateLocation(CGF, Loc,
3577 isOpenMPDistributeDirective(DKind)
3578 ? OMP_IDENT_WORK_DISTRIBUTE
3579 : isOpenMPLoopDirective(DKind)
3580 ? OMP_IDENT_WORK_LOOP
3581 : OMP_IDENT_WORK_SECTIONS),
3582 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003583 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3584 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003585}
3586
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003587void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3588 SourceLocation Loc,
3589 unsigned IVSize,
3590 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003591 if (!CGF.HaveInsertPoint())
3592 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003593 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003594 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003595 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3596}
3597
Alexander Musman92bdaab2015-03-12 13:37:50 +00003598llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3599 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003600 bool IVSigned, Address IL,
3601 Address LB, Address UB,
3602 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003603 // Call __kmpc_dispatch_next(
3604 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3605 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3606 // kmp_int[32|64] *p_stride);
3607 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003608 emitUpdateLocation(CGF, Loc),
3609 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003610 IL.getPointer(), // &isLastIter
3611 LB.getPointer(), // &Lower
3612 UB.getPointer(), // &Upper
3613 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003614 };
3615 llvm::Value *Call =
3616 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3617 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003618 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003619 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003620}
3621
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003622void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3623 llvm::Value *NumThreads,
3624 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003625 if (!CGF.HaveInsertPoint())
3626 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003627 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3628 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003629 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003630 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003631 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3632 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003633}
3634
Alexey Bataev7f210c62015-06-18 13:40:03 +00003635void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3636 OpenMPProcBindClauseKind ProcBind,
3637 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003638 if (!CGF.HaveInsertPoint())
3639 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003640 // Constants for proc bind value accepted by the runtime.
3641 enum ProcBindTy {
3642 ProcBindFalse = 0,
3643 ProcBindTrue,
3644 ProcBindMaster,
3645 ProcBindClose,
3646 ProcBindSpread,
3647 ProcBindIntel,
3648 ProcBindDefault
3649 } RuntimeProcBind;
3650 switch (ProcBind) {
3651 case OMPC_PROC_BIND_master:
3652 RuntimeProcBind = ProcBindMaster;
3653 break;
3654 case OMPC_PROC_BIND_close:
3655 RuntimeProcBind = ProcBindClose;
3656 break;
3657 case OMPC_PROC_BIND_spread:
3658 RuntimeProcBind = ProcBindSpread;
3659 break;
3660 case OMPC_PROC_BIND_unknown:
3661 llvm_unreachable("Unsupported proc_bind value.");
3662 }
3663 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3664 llvm::Value *Args[] = {
3665 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3666 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3667 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3668}
3669
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003670void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3671 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003672 if (!CGF.HaveInsertPoint())
3673 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003674 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003675 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3676 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003677}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003678
Alexey Bataev62b63b12015-03-10 07:28:44 +00003679namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003680/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003681enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003682 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003683 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003684 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003685 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003686 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003687 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003688 /// Function with call of destructors for private variables.
3689 Data1,
3690 /// Task priority.
3691 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003692 /// (Taskloops only) Lower bound.
3693 KmpTaskTLowerBound,
3694 /// (Taskloops only) Upper bound.
3695 KmpTaskTUpperBound,
3696 /// (Taskloops only) Stride.
3697 KmpTaskTStride,
3698 /// (Taskloops only) Is last iteration flag.
3699 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003700 /// (Taskloops only) Reduction data.
3701 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003702};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003703} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003704
Samuel Antaoee8fb302016-01-06 13:42:12 +00003705bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003706 return OffloadEntriesTargetRegion.empty() &&
3707 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003708}
3709
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003710/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003711void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3712 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3713 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003714 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003715 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3716 "only required for the device "
3717 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003718 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003719 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003720 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003721 ++OffloadingEntriesNum;
3722}
3723
3724void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3725 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3726 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003727 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003728 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003729 // If we are emitting code for a target, the entry is already initialized,
3730 // only has to be registered.
3731 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003732 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3733 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3734 DiagnosticsEngine::Error,
3735 "Unable to find target region on line '%0' in the device code.");
3736 CGM.getDiags().Report(DiagID) << LineNum;
3737 return;
3738 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003739 auto &Entry =
3740 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003741 assert(Entry.isValid() && "Entry not initialized!");
3742 Entry.setAddress(Addr);
3743 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003744 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003745 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003746 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003747 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003748 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003749 }
3750}
3751
3752bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003753 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3754 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003755 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3756 if (PerDevice == OffloadEntriesTargetRegion.end())
3757 return false;
3758 auto PerFile = PerDevice->second.find(FileID);
3759 if (PerFile == PerDevice->second.end())
3760 return false;
3761 auto PerParentName = PerFile->second.find(ParentName);
3762 if (PerParentName == PerFile->second.end())
3763 return false;
3764 auto PerLine = PerParentName->second.find(LineNum);
3765 if (PerLine == PerParentName->second.end())
3766 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003767 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003768 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003769 return false;
3770 return true;
3771}
3772
3773void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3774 const OffloadTargetRegionEntryInfoActTy &Action) {
3775 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003776 for (const auto &D : OffloadEntriesTargetRegion)
3777 for (const auto &F : D.second)
3778 for (const auto &P : F.second)
3779 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003780 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003781}
3782
Alexey Bataev03f270c2018-03-30 18:31:07 +00003783void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3784 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3785 OMPTargetGlobalVarEntryKind Flags,
3786 unsigned Order) {
3787 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3788 "only required for the device "
3789 "code generation.");
3790 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3791 ++OffloadingEntriesNum;
3792}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003793
Alexey Bataev03f270c2018-03-30 18:31:07 +00003794void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3795 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3796 CharUnits VarSize,
3797 OMPTargetGlobalVarEntryKind Flags,
3798 llvm::GlobalValue::LinkageTypes Linkage) {
3799 if (CGM.getLangOpts().OpenMPIsDevice) {
3800 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3801 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3802 "Entry not initialized!");
3803 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3804 "Resetting with the new address.");
Alexey Bataev8259cc32019-03-12 20:05:17 +00003805 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName)) {
3806 if (Entry.getVarSize().isZero()) {
3807 Entry.setVarSize(VarSize);
3808 Entry.setLinkage(Linkage);
3809 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003810 return;
Alexey Bataev8259cc32019-03-12 20:05:17 +00003811 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003812 Entry.setVarSize(VarSize);
3813 Entry.setLinkage(Linkage);
Alexey Bataev8259cc32019-03-12 20:05:17 +00003814 Entry.setAddress(Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003815 } else {
Alexey Bataev8259cc32019-03-12 20:05:17 +00003816 if (hasDeviceGlobalVarEntryInfo(VarName)) {
3817 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3818 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3819 "Entry not initialized!");
3820 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3821 "Resetting with the new address.");
3822 if (Entry.getVarSize().isZero()) {
3823 Entry.setVarSize(VarSize);
3824 Entry.setLinkage(Linkage);
3825 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003826 return;
Alexey Bataev8259cc32019-03-12 20:05:17 +00003827 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003828 OffloadEntriesDeviceGlobalVar.try_emplace(
3829 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3830 ++OffloadingEntriesNum;
3831 }
3832}
3833
3834void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3835 actOnDeviceGlobalVarEntriesInfo(
3836 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3837 // Scan all target region entries and perform the provided action.
3838 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3839 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003840}
3841
3842llvm::Function *
3843CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003844 // If we don't have entries or if we are emitting code for the device, we
3845 // don't need to do anything.
3846 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3847 return nullptr;
3848
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003849 llvm::Module &M = CGM.getModule();
3850 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003851
3852 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003853 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003854
3855 // We should be creating an offloading descriptor only if there are devices
3856 // specified.
3857 assert(!Devices.empty() && "No OpenMP offloading devices??");
3858
3859 // Create the external variables that will point to the begin and end of the
3860 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003861 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003862 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003863 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003864 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003865 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003866 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003867 EntriesBeginName);
3868 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3869 auto *HostEntriesEnd =
3870 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3871 llvm::GlobalValue::ExternalLinkage,
3872 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003873
3874 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003875 auto *DeviceImageTy = cast<llvm::StructType>(
3876 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003877 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003878 ConstantArrayBuilder DeviceImagesEntries =
3879 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003880
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003881 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003882 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003883 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003884 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003885 M, CGM.Int8Ty, /*isConstant=*/true,
3886 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003887 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3888 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003889 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003890 M, CGM.Int8Ty, /*isConstant=*/true,
3891 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003892 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003893
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003894 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3895 HostEntriesEnd};
3896 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3897 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003898 }
3899
3900 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003901 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003902 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003903 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3904 CGM.getPointerAlign(),
3905 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003906 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003907
3908 // This is a Zero array to be used in the creation of the constant expressions
3909 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3910 llvm::Constant::getNullValue(CGM.Int32Ty)};
3911
3912 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003913 llvm::Constant *Data[] = {
3914 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3915 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3916 DeviceImages, Index),
3917 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003918 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003919 llvm::GlobalVariable *Desc = createGlobalStruct(
3920 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003921
3922 // Emit code to register or unregister the descriptor at execution
3923 // startup or closing, respectively.
3924
Alexey Bataev03f270c2018-03-30 18:31:07 +00003925 llvm::Function *UnRegFn;
3926 {
3927 FunctionArgList Args;
3928 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3929 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003930
Alexey Bataev03f270c2018-03-30 18:31:07 +00003931 CodeGenFunction CGF(CGM);
3932 // Disable debug info for global (de-)initializer because they are not part
3933 // of some particular construct.
3934 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003935 const auto &FI =
3936 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3937 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003938 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3939 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003940 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3941 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3942 Desc);
3943 CGF.FinishFunction();
3944 }
3945 llvm::Function *RegFn;
3946 {
3947 CodeGenFunction CGF(CGM);
3948 // Disable debug info for global (de-)initializer because they are not part
3949 // of some particular construct.
3950 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003951 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003952 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003953
3954 // Encode offload target triples into the registration function name. It
3955 // will serve as a comdat key for the registration/unregistration code for
3956 // this particular combination of offloading targets.
3957 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3958 RegFnNameParts[0] = "omp_offloading";
3959 RegFnNameParts[1] = "descriptor_reg";
3960 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3961 [](const llvm::Triple &T) -> const std::string& {
3962 return T.getTriple();
3963 });
3964 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3965 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003966 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003967 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3968 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3969 // Create a variable to drive the registration and unregistration of the
3970 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3971 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3972 SourceLocation(), nullptr, C.CharTy,
3973 ImplicitParamDecl::Other);
3974 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3975 CGF.FinishFunction();
3976 }
George Rokos29d0f002017-05-27 03:03:13 +00003977 if (CGM.supportsCOMDAT()) {
3978 // It is sufficient to call registration function only once, so create a
3979 // COMDAT group for registration/unregistration functions and associated
3980 // data. That would reduce startup time and code size. Registration
3981 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003982 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003983 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3984 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3985 RegFn->setComdat(ComdatKey);
3986 UnRegFn->setComdat(ComdatKey);
3987 DeviceImages->setComdat(ComdatKey);
3988 Desc->setComdat(ComdatKey);
3989 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003990 return RegFn;
3991}
3992
Alexey Bataev03f270c2018-03-30 18:31:07 +00003993void CGOpenMPRuntime::createOffloadEntry(
3994 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3995 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003996 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003997 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003998 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003999
4000 // Create constant string with the name.
4001 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
4002
Alexey Bataev18fa2322018-05-02 14:20:50 +00004003 std::string StringName = getName({"omp_offloading", "entry_name"});
4004 auto *Str = new llvm::GlobalVariable(
4005 M, StrPtrInit->getType(), /*isConstant=*/true,
4006 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004007 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004008
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004009 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
4010 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
4011 llvm::ConstantInt::get(CGM.SizeTy, Size),
4012 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
4013 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00004014 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00004015 llvm::GlobalVariable *Entry = createGlobalStruct(
4016 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
4017 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004018
4019 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00004020 std::string Section = getName({"omp_offloading", "entries"});
4021 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004022}
4023
4024void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
4025 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00004026 // can easily figure out what to emit. The produced metadata looks like
4027 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004028 //
4029 // !omp_offload.info = !{!1, ...}
4030 //
4031 // Right now we only generate metadata for function that contain target
4032 // regions.
4033
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004034 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004035 if (OffloadEntriesInfoManager.empty())
4036 return;
4037
4038 llvm::Module &M = CGM.getModule();
4039 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00004040 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00004041 OrderedEntries(OffloadEntriesInfoManager.size());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004042 llvm::SmallVector<StringRef, 16> ParentFunctions(
4043 OffloadEntriesInfoManager.size());
Samuel Antaoee8fb302016-01-06 13:42:12 +00004044
Simon Pilgrim2c518802017-03-30 14:13:19 +00004045 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004046 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004047 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004048 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004049 };
4050
Alexey Bataev03f270c2018-03-30 18:31:07 +00004051 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
4052
4053 // Create the offloading info metadata node.
4054 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004055
4056 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00004057 auto &&TargetRegionMetadataEmitter =
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004058 [&C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt, &GetMDString](
Alexey Bataev03f270c2018-03-30 18:31:07 +00004059 unsigned DeviceID, unsigned FileID, StringRef ParentName,
4060 unsigned Line,
4061 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
4062 // Generate metadata for target regions. Each entry of this metadata
4063 // contains:
4064 // - Entry 0 -> Kind of this type of metadata (0).
4065 // - Entry 1 -> Device ID of the file where the entry was identified.
4066 // - Entry 2 -> File ID of the file where the entry was identified.
4067 // - Entry 3 -> Mangled name of the function where the entry was
4068 // identified.
4069 // - Entry 4 -> Line in the file where the entry was identified.
4070 // - Entry 5 -> Order the entry was created.
4071 // The first element of the metadata node is the kind.
4072 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
4073 GetMDInt(FileID), GetMDString(ParentName),
4074 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00004075
Alexey Bataev03f270c2018-03-30 18:31:07 +00004076 // Save this entry in the right position of the ordered entries array.
4077 OrderedEntries[E.getOrder()] = &E;
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004078 ParentFunctions[E.getOrder()] = ParentName;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004079
Alexey Bataev03f270c2018-03-30 18:31:07 +00004080 // Add metadata to the named metadata node.
4081 MD->addOperand(llvm::MDNode::get(C, Ops));
4082 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00004083
4084 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
4085 TargetRegionMetadataEmitter);
4086
Alexey Bataev03f270c2018-03-30 18:31:07 +00004087 // Create function that emits metadata for each device global variable entry;
4088 auto &&DeviceGlobalVarMetadataEmitter =
4089 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
4090 MD](StringRef MangledName,
4091 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
4092 &E) {
4093 // Generate metadata for global variables. Each entry of this metadata
4094 // contains:
4095 // - Entry 0 -> Kind of this type of metadata (1).
4096 // - Entry 1 -> Mangled name of the variable.
4097 // - Entry 2 -> Declare target kind.
4098 // - Entry 3 -> Order the entry was created.
4099 // The first element of the metadata node is the kind.
4100 llvm::Metadata *Ops[] = {
4101 GetMDInt(E.getKind()), GetMDString(MangledName),
4102 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
4103
4104 // Save this entry in the right position of the ordered entries array.
4105 OrderedEntries[E.getOrder()] = &E;
4106
4107 // Add metadata to the named metadata node.
4108 MD->addOperand(llvm::MDNode::get(C, Ops));
4109 };
4110
4111 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
4112 DeviceGlobalVarMetadataEmitter);
4113
4114 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004115 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004116 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00004117 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
4118 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004119 if (!CE->getID() || !CE->getAddress()) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004120 // Do not blame the entry if the parent funtion is not emitted.
4121 StringRef FnName = ParentFunctions[CE->getOrder()];
4122 if (!CGM.GetGlobalValue(FnName))
4123 continue;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004124 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4125 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00004126 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004127 "address or the ID is invalid.");
4128 CGM.getDiags().Report(DiagID);
4129 continue;
4130 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00004131 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004132 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
4133 } else if (const auto *CE =
4134 dyn_cast<OffloadEntriesInfoManagerTy::
4135 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004136 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
4137 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4138 CE->getFlags());
4139 switch (Flags) {
4140 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
4141 if (!CE->getAddress()) {
4142 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4143 DiagnosticsEngine::Error,
4144 "Offloading entry for declare target variable is incorrect: the "
4145 "address is invalid.");
4146 CGM.getDiags().Report(DiagID);
4147 continue;
4148 }
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00004149 // The vaiable has no definition - no need to add the entry.
4150 if (CE->getVarSize().isZero())
4151 continue;
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004152 break;
4153 }
4154 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
4155 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4156 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4157 "Declaret target link address is set.");
4158 if (CGM.getLangOpts().OpenMPIsDevice)
4159 continue;
4160 if (!CE->getAddress()) {
4161 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4162 DiagnosticsEngine::Error,
4163 "Offloading entry for declare target variable is incorrect: the "
4164 "address is invalid.");
4165 CGM.getDiags().Report(DiagID);
4166 continue;
4167 }
4168 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004169 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004170 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004171 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004172 CE->getLinkage());
4173 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004174 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004175 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004176 }
4177}
4178
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004179/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004180/// metadata.
4181void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4182 // If we are in target mode, load the metadata from the host IR. This code has
4183 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4184
4185 if (!CGM.getLangOpts().OpenMPIsDevice)
4186 return;
4187
4188 if (CGM.getLangOpts().OMPHostIRFile.empty())
4189 return;
4190
4191 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004192 if (auto EC = Buf.getError()) {
4193 CGM.getDiags().Report(diag::err_cannot_open_file)
4194 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004195 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004196 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004197
4198 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004199 auto ME = expectedToErrorOrAndEmitErrors(
4200 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004201
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004202 if (auto EC = ME.getError()) {
4203 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4204 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4205 CGM.getDiags().Report(DiagID)
4206 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004207 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004208 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004209
4210 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4211 if (!MD)
4212 return;
4213
George Burgess IV00f70bd2018-03-01 05:43:23 +00004214 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004215 auto &&GetMDInt = [MN](unsigned Idx) {
4216 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004217 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4218 };
4219
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004220 auto &&GetMDString = [MN](unsigned Idx) {
4221 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004222 return V->getString();
4223 };
4224
Alexey Bataev03f270c2018-03-30 18:31:07 +00004225 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004226 default:
4227 llvm_unreachable("Unexpected metadata!");
4228 break;
4229 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004230 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004231 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004232 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4233 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4234 /*Order=*/GetMDInt(5));
4235 break;
4236 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4237 OffloadingEntryInfoDeviceGlobalVar:
4238 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4239 /*MangledName=*/GetMDString(1),
4240 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4241 /*Flags=*/GetMDInt(2)),
4242 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004243 break;
4244 }
4245 }
4246}
4247
Alexey Bataev62b63b12015-03-10 07:28:44 +00004248void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4249 if (!KmpRoutineEntryPtrTy) {
4250 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004251 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004252 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4253 FunctionProtoType::ExtProtoInfo EPI;
4254 KmpRoutineEntryPtrQTy = C.getPointerType(
4255 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4256 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4257 }
4258}
4259
Samuel Antaoee8fb302016-01-06 13:42:12 +00004260QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004261 // Make sure the type of the entry is already created. This is the type we
4262 // have to create:
4263 // struct __tgt_offload_entry{
4264 // void *addr; // Pointer to the offload entry info.
4265 // // (function or global)
4266 // char *name; // Name of the function or global.
4267 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004268 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4269 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004270 // };
4271 if (TgtOffloadEntryQTy.isNull()) {
4272 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004273 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004274 RD->startDefinition();
4275 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4276 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4277 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004278 addFieldToRecordDecl(
4279 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4280 addFieldToRecordDecl(
4281 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004282 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004283 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004284 TgtOffloadEntryQTy = C.getRecordType(RD);
4285 }
4286 return TgtOffloadEntryQTy;
4287}
4288
4289QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4290 // These are the types we need to build:
4291 // struct __tgt_device_image{
4292 // void *ImageStart; // Pointer to the target code start.
4293 // void *ImageEnd; // Pointer to the target code end.
4294 // // We also add the host entries to the device image, as it may be useful
4295 // // for the target runtime to have access to that information.
4296 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4297 // // the entries.
4298 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4299 // // entries (non inclusive).
4300 // };
4301 if (TgtDeviceImageQTy.isNull()) {
4302 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004303 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004304 RD->startDefinition();
4305 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4306 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4307 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4308 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4309 RD->completeDefinition();
4310 TgtDeviceImageQTy = C.getRecordType(RD);
4311 }
4312 return TgtDeviceImageQTy;
4313}
4314
4315QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4316 // struct __tgt_bin_desc{
4317 // int32_t NumDevices; // Number of devices supported.
4318 // __tgt_device_image *DeviceImages; // Arrays of device images
4319 // // (one per device).
4320 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4321 // // entries.
4322 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4323 // // entries (non inclusive).
4324 // };
4325 if (TgtBinaryDescriptorQTy.isNull()) {
4326 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004327 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004328 RD->startDefinition();
4329 addFieldToRecordDecl(
4330 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4331 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4332 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4333 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4334 RD->completeDefinition();
4335 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4336 }
4337 return TgtBinaryDescriptorQTy;
4338}
4339
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004340namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004341struct PrivateHelpersTy {
4342 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4343 const VarDecl *PrivateElemInit)
4344 : Original(Original), PrivateCopy(PrivateCopy),
4345 PrivateElemInit(PrivateElemInit) {}
4346 const VarDecl *Original;
4347 const VarDecl *PrivateCopy;
4348 const VarDecl *PrivateElemInit;
4349};
4350typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004351} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004352
Alexey Bataev9e034042015-05-05 04:05:12 +00004353static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004354createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004355 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004356 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004357 // Build struct .kmp_privates_t. {
4358 // /* private vars */
4359 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004360 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004361 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004362 for (const auto &Pair : Privates) {
4363 const VarDecl *VD = Pair.second.Original;
4364 QualType Type = VD->getType().getNonReferenceType();
4365 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004366 if (VD->hasAttrs()) {
4367 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4368 E(VD->getAttrs().end());
4369 I != E; ++I)
4370 FD->addAttr(*I);
4371 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004372 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004373 RD->completeDefinition();
4374 return RD;
4375 }
4376 return nullptr;
4377}
4378
Alexey Bataev9e034042015-05-05 04:05:12 +00004379static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004380createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4381 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004382 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004383 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004384 // Build struct kmp_task_t {
4385 // void * shareds;
4386 // kmp_routine_entry_t routine;
4387 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004388 // kmp_cmplrdata_t data1;
4389 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004390 // For taskloops additional fields:
4391 // kmp_uint64 lb;
4392 // kmp_uint64 ub;
4393 // kmp_int64 st;
4394 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004395 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004396 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004397 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004398 UD->startDefinition();
4399 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4400 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4401 UD->completeDefinition();
4402 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004403 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004404 RD->startDefinition();
4405 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4406 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4407 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004408 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4409 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004410 if (isOpenMPTaskLoopDirective(Kind)) {
4411 QualType KmpUInt64Ty =
4412 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4413 QualType KmpInt64Ty =
4414 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4415 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4416 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4417 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4418 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004419 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004420 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004421 RD->completeDefinition();
4422 return RD;
4423}
4424
4425static RecordDecl *
4426createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004427 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004428 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004429 // Build struct kmp_task_t_with_privates {
4430 // kmp_task_t task_data;
4431 // .kmp_privates_t. privates;
4432 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004433 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004434 RD->startDefinition();
4435 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004436 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004437 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004438 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004439 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004440}
4441
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004442/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004443/// argument.
4444/// \code
4445/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004446/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004447/// For taskloops:
4448/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004449/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004450/// return 0;
4451/// }
4452/// \endcode
James Y Knight9871db02019-02-05 16:42:33 +00004453static llvm::Function *
Alexey Bataev62b63b12015-03-10 07:28:44 +00004454emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004455 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4456 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004457 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
James Y Knight9871db02019-02-05 16:42:33 +00004458 QualType SharedsPtrTy, llvm::Function *TaskFunction,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004459 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004460 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004461 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004462 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4463 ImplicitParamDecl::Other);
4464 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4465 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4466 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004467 Args.push_back(&GtidArg);
4468 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004469 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004470 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004471 llvm::FunctionType *TaskEntryTy =
4472 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004473 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4474 auto *TaskEntry = llvm::Function::Create(
4475 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004476 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004477 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004478 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004479 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4480 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004481
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004482 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004483 // tt,
4484 // For taskloops:
4485 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4486 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004487 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004488 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004489 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4490 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4491 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004492 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004493 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004494 LValue Base =
4495 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004496 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004497 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004498 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4499 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004500
4501 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004502 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4503 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004504 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004505 CGF.ConvertTypeForMem(SharedsPtrTy));
4506
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004507 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4508 llvm::Value *PrivatesParam;
4509 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004510 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004511 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004512 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004513 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004514 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004515 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004516
Alexey Bataev7292c292016-04-25 12:22:29 +00004517 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4518 TaskPrivatesMap,
4519 CGF.Builder
4520 .CreatePointerBitCastOrAddrSpaceCast(
4521 TDBase.getAddress(), CGF.VoidPtrTy)
4522 .getPointer()};
4523 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4524 std::end(CommonArgs));
4525 if (isOpenMPTaskLoopDirective(Kind)) {
4526 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004527 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4528 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004529 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004530 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4531 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004532 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004533 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4534 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004535 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004536 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4537 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004538 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004539 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4540 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004541 CallArgs.push_back(LBParam);
4542 CallArgs.push_back(UBParam);
4543 CallArgs.push_back(StParam);
4544 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004545 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004546 }
4547 CallArgs.push_back(SharedsParam);
4548
Alexey Bataev3c595a62017-08-14 15:01:03 +00004549 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4550 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004551 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4552 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004553 CGF.FinishFunction();
4554 return TaskEntry;
4555}
4556
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004557static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4558 SourceLocation Loc,
4559 QualType KmpInt32Ty,
4560 QualType KmpTaskTWithPrivatesPtrQTy,
4561 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004562 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004563 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004564 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4565 ImplicitParamDecl::Other);
4566 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4567 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4568 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004569 Args.push_back(&GtidArg);
4570 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004571 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004572 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004573 llvm::FunctionType *DestructorFnTy =
4574 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004575 std::string Name =
4576 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004577 auto *DestructorFn =
4578 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004579 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004580 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004581 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004582 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004583 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004584 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004585 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004586
Alexey Bataev31300ed2016-02-04 11:27:03 +00004587 LValue Base = CGF.EmitLoadOfPointerLValue(
4588 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4589 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004590 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004591 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4592 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004593 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004594 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004595 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004596 if (QualType::DestructionKind DtorKind =
4597 Field->getType().isDestructedType()) {
4598 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004599 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4600 }
4601 }
4602 CGF.FinishFunction();
4603 return DestructorFn;
4604}
4605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004606/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004607/// firstprivate variables.
4608/// \code
4609/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4610/// **noalias priv1,..., <tyn> **noalias privn) {
4611/// *priv1 = &.privates.priv1;
4612/// ...;
4613/// *privn = &.privates.privn;
4614/// }
4615/// \endcode
4616static llvm::Value *
4617emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004618 ArrayRef<const Expr *> PrivateVars,
4619 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004620 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004621 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004622 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004623 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004624 FunctionArgList Args;
4625 ImplicitParamDecl TaskPrivatesArg(
4626 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004627 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4628 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004629 Args.push_back(&TaskPrivatesArg);
4630 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4631 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004632 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004633 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004634 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4635 C.getPointerType(C.getPointerType(E->getType()))
4636 .withConst()
4637 .withRestrict(),
4638 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004639 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004640 PrivateVarsPos[VD] = Counter;
4641 ++Counter;
4642 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004643 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004644 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004645 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4646 C.getPointerType(C.getPointerType(E->getType()))
4647 .withConst()
4648 .withRestrict(),
4649 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004650 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004651 PrivateVarsPos[VD] = Counter;
4652 ++Counter;
4653 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004654 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004655 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004656 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4657 C.getPointerType(C.getPointerType(E->getType()))
4658 .withConst()
4659 .withRestrict(),
4660 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004661 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004662 PrivateVarsPos[VD] = Counter;
4663 ++Counter;
4664 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004665 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004666 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004667 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004668 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004669 std::string Name =
4670 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004671 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004672 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4673 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004674 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004675 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004676 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004677 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004678 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004679 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004680 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004681 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004682
4683 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004684 LValue Base = CGF.EmitLoadOfPointerLValue(
4685 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4686 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004687 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004688 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004689 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4690 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4691 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4692 LValue RefLVal =
4693 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4694 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004695 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004696 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004697 ++Counter;
4698 }
4699 CGF.FinishFunction();
4700 return TaskPrivatesMap;
4701}
4702
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004703static bool stable_sort_comparator(const PrivateDataTy P1,
4704 const PrivateDataTy P2) {
4705 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004706}
4707
Alexey Bataevf93095a2016-05-05 08:46:22 +00004708/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004709static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004710 const OMPExecutableDirective &D,
4711 Address KmpTaskSharedsPtr, LValue TDBase,
4712 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4713 QualType SharedsTy, QualType SharedsPtrTy,
4714 const OMPTaskDataTy &Data,
4715 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004716 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004717 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4718 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004719 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4720 ? OMPD_taskloop
4721 : OMPD_task;
4722 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4723 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004724 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004725 bool IsTargetTask =
4726 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4727 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4728 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4729 // PointersArray and SizesArray. The original variables for these arrays are
4730 // not captured and we get their addresses explicitly.
4731 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004732 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004733 SrcBase = CGF.MakeAddrLValue(
4734 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4735 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4736 SharedsTy);
4737 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004738 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004739 for (const PrivateDataTy &Pair : Privates) {
4740 const VarDecl *VD = Pair.second.PrivateCopy;
4741 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004742 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4743 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004744 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004745 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4746 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004747 // Check if the variable is the target-based BasePointersArray,
4748 // PointersArray or SizesArray.
4749 LValue SharedRefLValue;
Alexey Bataevab41ea62019-03-13 20:46:28 +00004750 QualType Type = PrivateLValue.getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004751 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004752 if (IsTargetTask && !SharedField) {
4753 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4754 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4755 cast<CapturedDecl>(OriginalVD->getDeclContext())
4756 ->getNumParams() == 0 &&
4757 isa<TranslationUnitDecl>(
4758 cast<CapturedDecl>(OriginalVD->getDeclContext())
4759 ->getDeclContext()) &&
4760 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004761 SharedRefLValue =
4762 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4763 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004764 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4765 SharedRefLValue = CGF.MakeAddrLValue(
4766 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4767 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4768 SharedRefLValue.getTBAAInfo());
4769 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004770 if (Type->isArrayType()) {
4771 // Initialize firstprivate array.
4772 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4773 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004774 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004775 } else {
4776 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004777 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004778 CGF.EmitOMPAggregateAssign(
4779 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4780 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4781 Address SrcElement) {
4782 // Clean up any temporaries needed by the initialization.
4783 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4784 InitScope.addPrivate(
4785 Elem, [SrcElement]() -> Address { return SrcElement; });
4786 (void)InitScope.Privatize();
4787 // Emit initialization for single element.
4788 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4789 CGF, &CapturesInfo);
4790 CGF.EmitAnyExprToMem(Init, DestElement,
4791 Init->getType().getQualifiers(),
4792 /*IsInitializer=*/false);
4793 });
4794 }
4795 } else {
4796 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4797 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4798 return SharedRefLValue.getAddress();
4799 });
4800 (void)InitScope.Privatize();
4801 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4802 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4803 /*capturedByInit=*/false);
4804 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004805 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004806 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004807 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004808 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004809 ++FI;
4810 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004811}
4812
4813/// Check if duplication function is required for taskloops.
4814static bool checkInitIsRequired(CodeGenFunction &CGF,
4815 ArrayRef<PrivateDataTy> Privates) {
4816 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004817 for (const PrivateDataTy &Pair : Privates) {
4818 const VarDecl *VD = Pair.second.PrivateCopy;
4819 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004820 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4821 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004822 if (InitRequired)
4823 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004824 }
4825 return InitRequired;
4826}
4827
4828
4829/// Emit task_dup function (for initialization of
4830/// private/firstprivate/lastprivate vars and last_iter flag)
4831/// \code
4832/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4833/// lastpriv) {
4834/// // setup lastprivate flag
4835/// task_dst->last = lastpriv;
4836/// // could be constructor calls here...
4837/// }
4838/// \endcode
4839static llvm::Value *
4840emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4841 const OMPExecutableDirective &D,
4842 QualType KmpTaskTWithPrivatesPtrQTy,
4843 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4844 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4845 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4846 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004847 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004848 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004849 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4850 KmpTaskTWithPrivatesPtrQTy,
4851 ImplicitParamDecl::Other);
4852 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4853 KmpTaskTWithPrivatesPtrQTy,
4854 ImplicitParamDecl::Other);
4855 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4856 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004857 Args.push_back(&DstArg);
4858 Args.push_back(&SrcArg);
4859 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004860 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004861 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004862 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004863 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4864 auto *TaskDup = llvm::Function::Create(
4865 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004866 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004867 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004868 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004869 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4870 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004871
4872 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4873 CGF.GetAddrOfLocalVar(&DstArg),
4874 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4875 // task_dst->liter = lastpriv;
4876 if (WithLastIter) {
4877 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4878 LValue Base = CGF.EmitLValueForField(
4879 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4880 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4881 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4882 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4883 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4884 }
4885
4886 // Emit initial values for private copies (if any).
4887 assert(!Privates.empty());
4888 Address KmpTaskSharedsPtr = Address::invalid();
4889 if (!Data.FirstprivateVars.empty()) {
4890 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4891 CGF.GetAddrOfLocalVar(&SrcArg),
4892 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4893 LValue Base = CGF.EmitLValueForField(
4894 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4895 KmpTaskSharedsPtr = Address(
4896 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4897 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4898 KmpTaskTShareds)),
4899 Loc),
4900 CGF.getNaturalTypeAlignment(SharedsTy));
4901 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004902 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4903 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004904 CGF.FinishFunction();
4905 return TaskDup;
4906}
4907
Alexey Bataev8a831592016-05-10 10:36:51 +00004908/// Checks if destructor function is required to be generated.
4909/// \return true if cleanups are required, false otherwise.
4910static bool
4911checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4912 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004913 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4914 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4915 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004916 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4917 if (NeedsCleanup)
4918 break;
4919 }
4920 return NeedsCleanup;
4921}
4922
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004923CGOpenMPRuntime::TaskResultTy
4924CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4925 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00004926 llvm::Function *TaskFunction, QualType SharedsTy,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004927 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004928 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004929 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004930 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004931 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004932 for (const Expr *E : Data.PrivateVars) {
4933 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004934 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004935 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004936 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004937 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004938 ++I;
4939 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004940 I = Data.FirstprivateCopies.begin();
4941 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004942 for (const Expr *E : Data.FirstprivateVars) {
4943 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004944 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004945 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004946 PrivateHelpersTy(
4947 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004948 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004949 ++I;
4950 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004951 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004952 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004953 for (const Expr *E : Data.LastprivateVars) {
4954 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004955 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004956 C.getDeclAlign(VD),
4957 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004958 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004959 ++I;
4960 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004961 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004962 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004963 // Build type kmp_routine_entry_t (if not built yet).
4964 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004965 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004966 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4967 if (SavedKmpTaskloopTQTy.isNull()) {
4968 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4969 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4970 }
4971 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004972 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004973 assert((D.getDirectiveKind() == OMPD_task ||
4974 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4975 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4976 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004977 if (SavedKmpTaskTQTy.isNull()) {
4978 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4979 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4980 }
4981 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004982 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004983 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004984 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004985 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004986 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004987 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004988 QualType KmpTaskTWithPrivatesPtrQTy =
4989 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004990 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4991 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4992 KmpTaskTWithPrivatesTy->getPointerTo();
4993 llvm::Value *KmpTaskTWithPrivatesTySize =
4994 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004995 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4996
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004997 // Emit initial values for private copies (if any).
4998 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004999 llvm::Type *TaskPrivatesMapTy =
James Y Knight9871db02019-02-05 16:42:33 +00005000 std::next(TaskFunction->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00005001 if (!Privates.empty()) {
5002 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00005003 TaskPrivatesMap = emitTaskPrivateMappingFunction(
5004 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
5005 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00005006 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5007 TaskPrivatesMap, TaskPrivatesMapTy);
5008 } else {
5009 TaskPrivatesMap = llvm::ConstantPointerNull::get(
5010 cast<llvm::PointerType>(TaskPrivatesMapTy));
5011 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005012 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
5013 // kmp_task_t *tt);
James Y Knight9871db02019-02-05 16:42:33 +00005014 llvm::Function *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00005015 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
5016 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
5017 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00005018
5019 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
5020 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
5021 // kmp_routine_entry_t *task_entry);
5022 // Task flags. Format is taken from
James Y Knight5d71fc52019-01-29 16:37:27 +00005023 // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h,
Alexey Bataev62b63b12015-03-10 07:28:44 +00005024 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00005025 enum {
5026 TiedFlag = 0x1,
5027 FinalFlag = 0x2,
5028 DestructorsFlag = 0x8,
5029 PriorityFlag = 0x20
5030 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005031 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00005032 bool NeedsCleanup = false;
5033 if (!Privates.empty()) {
5034 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
5035 if (NeedsCleanup)
5036 Flags = Flags | DestructorsFlag;
5037 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00005038 if (Data.Priority.getInt())
5039 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005040 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005041 Data.Final.getPointer()
5042 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00005043 CGF.Builder.getInt32(FinalFlag),
5044 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005045 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00005046 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005047 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005048 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
5049 getThreadID(CGF, Loc), TaskFlags,
5050 KmpTaskTWithPrivatesTySize, SharedsSize,
5051 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5052 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005053 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00005054 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005055 llvm::Value *NewTaskNewTaskTTy =
5056 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5057 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005058 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
5059 KmpTaskTWithPrivatesQTy);
5060 LValue TDBase =
5061 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00005062 // Fill the data in the resulting kmp_task_t record.
5063 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00005064 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005065 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00005066 KmpTaskSharedsPtr =
5067 Address(CGF.EmitLoadOfScalar(
5068 CGF.EmitLValueForField(
5069 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
5070 KmpTaskTShareds)),
5071 Loc),
5072 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00005073 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
5074 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00005075 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005076 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005077 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00005078 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005079 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00005080 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
5081 SharedsTy, SharedsPtrTy, Data, Privates,
5082 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005083 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
5084 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
5085 Result.TaskDupFn = emitTaskDupFunction(
5086 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
5087 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
5088 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005089 }
5090 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00005091 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
5092 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00005093 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00005094 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005095 const RecordDecl *KmpCmplrdataUD =
5096 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00005097 if (NeedsCleanup) {
5098 llvm::Value *DestructorFn = emitDestructorsFunction(
5099 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
5100 KmpTaskTWithPrivatesQTy);
5101 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
5102 LValue DestructorsLV = CGF.EmitLValueForField(
5103 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
5104 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5105 DestructorFn, KmpRoutineEntryPtrTy),
5106 DestructorsLV);
5107 }
5108 // Set priority.
5109 if (Data.Priority.getInt()) {
5110 LValue Data2LV = CGF.EmitLValueForField(
5111 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
5112 LValue PriorityLV = CGF.EmitLValueForField(
5113 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
5114 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
5115 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005116 Result.NewTask = NewTask;
5117 Result.TaskEntry = TaskEntry;
5118 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
5119 Result.TDBase = TDBase;
5120 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
5121 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00005122}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005123
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005124void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
5125 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00005126 llvm::Function *TaskFunction,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005127 QualType SharedsTy, Address Shareds,
5128 const Expr *IfCond,
5129 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005130 if (!CGF.HaveInsertPoint())
5131 return;
5132
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005133 TaskResultTy Result =
5134 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5135 llvm::Value *NewTask = Result.NewTask;
James Y Knight9871db02019-02-05 16:42:33 +00005136 llvm::Function *TaskEntry = Result.TaskEntry;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005137 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
5138 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005139 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
5140 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005141 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00005142 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005143 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00005144 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005145 // Dependence kind for RTL.
Sergi Mateo Bellido31df1ad2019-02-04 07:33:19 +00005146 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3, DepMutexInOutSet = 0x4 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005147 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
5148 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005149 QualType FlagsTy =
5150 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005151 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
5152 if (KmpDependInfoTy.isNull()) {
5153 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
5154 KmpDependInfoRD->startDefinition();
5155 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
5156 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
5157 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
5158 KmpDependInfoRD->completeDefinition();
5159 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005160 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005161 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005162 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005163 // Define type kmp_depend_info[<Dependences.size()>];
5164 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005165 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005166 ArrayType::Normal, /*IndexTypeQuals=*/0);
5167 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005168 DependenciesArray =
5169 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005170 for (unsigned I = 0; I < NumDependencies; ++I) {
5171 const Expr *E = Data.Dependences[I].second;
5172 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005173 llvm::Value *Size;
5174 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005175 if (const auto *ASE =
5176 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005177 LValue UpAddrLVal =
5178 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5179 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005180 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005181 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005182 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005183 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5184 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005185 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005186 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005187 }
5188 LValue Base = CGF.MakeAddrLValue(
James Y Knight751fe282019-02-09 22:22:28 +00005189 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005190 KmpDependInfoTy);
5191 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005192 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005193 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005194 CGF.EmitStoreOfScalar(
5195 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5196 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005197 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005198 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005199 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5200 CGF.EmitStoreOfScalar(Size, LenLVal);
5201 // deps[i].flags = <Dependences[i].first>;
5202 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005203 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005204 case OMPC_DEPEND_in:
5205 DepKind = DepIn;
5206 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005207 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005208 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005209 case OMPC_DEPEND_inout:
5210 DepKind = DepInOut;
5211 break;
Sergi Mateo Bellido31df1ad2019-02-04 07:33:19 +00005212 case OMPC_DEPEND_mutexinoutset:
5213 DepKind = DepMutexInOutSet;
5214 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005215 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005216 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005217 case OMPC_DEPEND_unknown:
5218 llvm_unreachable("Unknown task dependence type");
5219 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005220 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005221 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5222 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5223 FlagsLVal);
5224 }
John McCall7f416cc2015-09-08 08:05:57 +00005225 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
James Y Knightf5f1b0e2019-02-08 15:34:12 +00005226 CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0), CGF.VoidPtrTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005227 }
5228
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005229 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005230 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005231 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5232 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5233 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5234 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005235 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5236 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005237 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5238 llvm::Value *DepTaskArgs[7];
5239 if (NumDependencies) {
5240 DepTaskArgs[0] = UpLoc;
5241 DepTaskArgs[1] = ThreadID;
5242 DepTaskArgs[2] = NewTask;
5243 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5244 DepTaskArgs[4] = DependenciesArray.getPointer();
5245 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5246 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5247 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005248 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5249 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005250 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005251 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005252 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005253 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005254 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5255 }
John McCall7f416cc2015-09-08 08:05:57 +00005256 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005257 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005258 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005259 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005260 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005261 TaskArgs);
5262 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005263 // Check if parent region is untied and build return for untied task;
5264 if (auto *Region =
5265 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5266 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005267 };
John McCall7f416cc2015-09-08 08:05:57 +00005268
5269 llvm::Value *DepWaitTaskArgs[6];
5270 if (NumDependencies) {
5271 DepWaitTaskArgs[0] = UpLoc;
5272 DepWaitTaskArgs[1] = ThreadID;
5273 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5274 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5275 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5276 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5277 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005278 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005279 NumDependencies, &DepWaitTaskArgs,
5280 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005281 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005282 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5283 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5284 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5285 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5286 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005287 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005288 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005289 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005290 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005291 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5292 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005293 Action.Enter(CGF);
5294 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005295 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005296 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005297 };
5298
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005299 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5300 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005301 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5302 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005303 RegionCodeGenTy RCG(CodeGen);
5304 CommonActionTy Action(
5305 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5306 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5307 RCG.setAction(Action);
5308 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005309 };
John McCall7f416cc2015-09-08 08:05:57 +00005310
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005311 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005312 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005313 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005314 RegionCodeGenTy ThenRCG(ThenCodeGen);
5315 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005316 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005317}
5318
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005319void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5320 const OMPLoopDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00005321 llvm::Function *TaskFunction,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005322 QualType SharedsTy, Address Shareds,
5323 const Expr *IfCond,
5324 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005325 if (!CGF.HaveInsertPoint())
5326 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005327 TaskResultTy Result =
5328 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005329 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005330 // libcall.
5331 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5332 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5333 // sched, kmp_uint64 grainsize, void *task_dup);
5334 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5335 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5336 llvm::Value *IfVal;
5337 if (IfCond) {
5338 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5339 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005340 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005341 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005342 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005343
5344 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005345 Result.TDBase,
5346 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005347 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005348 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5349 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5350 /*IsInitializer=*/true);
5351 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005352 Result.TDBase,
5353 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005354 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005355 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5356 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5357 /*IsInitializer=*/true);
5358 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005359 Result.TDBase,
5360 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005361 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005362 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5363 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5364 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005365 // Store reductions address.
5366 LValue RedLVal = CGF.EmitLValueForField(
5367 Result.TDBase,
5368 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005369 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005370 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005371 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005372 CGF.EmitNullInitialization(RedLVal.getAddress(),
5373 CGF.getContext().VoidPtrTy);
5374 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005375 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005376 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005377 UpLoc,
5378 ThreadID,
5379 Result.NewTask,
5380 IfVal,
5381 LBLVal.getPointer(),
5382 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005383 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataevac6e4de2018-10-24 19:06:37 +00005384 llvm::ConstantInt::getSigned(
5385 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005386 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005387 CGF.IntTy, Data.Schedule.getPointer()
5388 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005389 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005390 Data.Schedule.getPointer()
5391 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005392 /*isSigned=*/false)
5393 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005394 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5395 Result.TaskDupFn, CGF.VoidPtrTy)
5396 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005397 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5398}
5399
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005400/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005401/// array sections) LHS op = RHS.
5402/// \param Type Type of array.
5403/// \param LHSVar Variable on the left side of the reduction operation
5404/// (references element of array in original variable).
5405/// \param RHSVar Variable on the right side of the reduction operation
5406/// (references element of array in original variable).
5407/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5408/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005409static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005410 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5411 const VarDecl *RHSVar,
5412 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5413 const Expr *, const Expr *)> &RedOpGen,
5414 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5415 const Expr *UpExpr = nullptr) {
5416 // Perform element-by-element initialization.
5417 QualType ElementTy;
5418 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5419 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5420
5421 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005422 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5423 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005424
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005425 llvm::Value *RHSBegin = RHSAddr.getPointer();
5426 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005427 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005428 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005429 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005430 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5431 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5432 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005433 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5434 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5435
5436 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005437 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005438 CGF.EmitBlock(BodyBB);
5439
5440 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5441
5442 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5443 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5444 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5445 Address RHSElementCurrent =
5446 Address(RHSElementPHI,
5447 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5448
5449 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5450 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5451 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5452 Address LHSElementCurrent =
5453 Address(LHSElementPHI,
5454 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5455
5456 // Emit copy.
5457 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005458 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5459 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005460 Scope.Privatize();
5461 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5462 Scope.ForceCleanup();
5463
5464 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005465 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005466 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005467 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005468 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5469 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005470 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005471 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5472 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5473 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5474 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5475
5476 // Done.
5477 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5478}
5479
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005480/// Emit reduction combiner. If the combiner is a simple expression emit it as
5481/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5482/// UDR combiner function.
5483static void emitReductionCombiner(CodeGenFunction &CGF,
5484 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005485 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5486 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5487 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005488 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005489 if (const auto *DRD =
5490 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005491 std::pair<llvm::Function *, llvm::Function *> Reduction =
5492 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5493 RValue Func = RValue::get(Reduction.first);
5494 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5495 CGF.EmitIgnoredExpr(ReductionOp);
5496 return;
5497 }
5498 CGF.EmitIgnoredExpr(ReductionOp);
5499}
5500
James Y Knight9871db02019-02-05 16:42:33 +00005501llvm::Function *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00005502 SourceLocation Loc, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
5503 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
5504 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005505 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005506
5507 // void reduction_func(void *LHSArg, void *RHSArg);
5508 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005509 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5510 ImplicitParamDecl::Other);
5511 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5512 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005513 Args.push_back(&LHSArg);
5514 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005515 const auto &CGFI =
5516 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005517 std::string Name = getName({"omp", "reduction", "reduction_func"});
5518 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5519 llvm::GlobalValue::InternalLinkage, Name,
5520 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005521 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005522 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005523 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005524 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005525
5526 // Dst = (void*[n])(LHSArg);
5527 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005528 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5529 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5530 ArgsType), CGF.getPointerAlign());
5531 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5532 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5533 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005534
5535 // ...
5536 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5537 // ...
5538 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005539 auto IPriv = Privates.begin();
5540 unsigned Idx = 0;
5541 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005542 const auto *RHSVar =
5543 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5544 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005545 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005546 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005547 const auto *LHSVar =
5548 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5549 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005550 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005551 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005552 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005553 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005554 // Get array size and emit VLA type.
5555 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00005556 Address Elem = CGF.Builder.CreateConstArrayGEP(LHS, Idx);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005557 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005558 const VariableArrayType *VLA =
5559 CGF.getContext().getAsVariableArrayType(PrivTy);
5560 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005561 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005562 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005563 CGF.EmitVariablyModifiedType(PrivTy);
5564 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005565 }
5566 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005567 IPriv = Privates.begin();
5568 auto ILHS = LHSExprs.begin();
5569 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005570 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005571 if ((*IPriv)->getType()->isArrayType()) {
5572 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005573 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5574 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005575 EmitOMPAggregateReduction(
5576 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5577 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5578 emitReductionCombiner(CGF, E);
5579 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005580 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005581 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005582 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005583 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005584 ++IPriv;
5585 ++ILHS;
5586 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005587 }
5588 Scope.ForceCleanup();
5589 CGF.FinishFunction();
5590 return Fn;
5591}
5592
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005593void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5594 const Expr *ReductionOp,
5595 const Expr *PrivateRef,
5596 const DeclRefExpr *LHS,
5597 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005598 if (PrivateRef->getType()->isArrayType()) {
5599 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005600 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5601 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005602 EmitOMPAggregateReduction(
5603 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5604 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5605 emitReductionCombiner(CGF, ReductionOp);
5606 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005607 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005608 // Emit reduction for array subscript or single variable.
5609 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005610 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005611}
5612
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005613void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005614 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005615 ArrayRef<const Expr *> LHSExprs,
5616 ArrayRef<const Expr *> RHSExprs,
5617 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005618 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005619 if (!CGF.HaveInsertPoint())
5620 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005621
5622 bool WithNowait = Options.WithNowait;
5623 bool SimpleReduction = Options.SimpleReduction;
5624
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005625 // Next code should be emitted for reduction:
5626 //
5627 // static kmp_critical_name lock = { 0 };
5628 //
5629 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5630 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5631 // ...
5632 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5633 // *(Type<n>-1*)rhs[<n>-1]);
5634 // }
5635 //
5636 // ...
5637 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5638 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5639 // RedList, reduce_func, &<lock>)) {
5640 // case 1:
5641 // ...
5642 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5643 // ...
5644 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5645 // break;
5646 // case 2:
5647 // ...
5648 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5649 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005650 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005651 // break;
5652 // default:;
5653 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005654 //
5655 // if SimpleReduction is true, only the next code is generated:
5656 // ...
5657 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5658 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005659
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005660 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005661
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005662 if (SimpleReduction) {
5663 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005664 auto IPriv = Privates.begin();
5665 auto ILHS = LHSExprs.begin();
5666 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005667 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005668 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5669 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005670 ++IPriv;
5671 ++ILHS;
5672 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005673 }
5674 return;
5675 }
5676
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005677 // 1. Build a list of reduction variables.
5678 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005679 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005680 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005681 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005682 // Reserve place for array size.
5683 ++Size;
5684 }
5685 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005686 QualType ReductionArrayTy =
5687 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5688 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005689 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005690 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005691 auto IPriv = Privates.begin();
5692 unsigned Idx = 0;
5693 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
James Y Knight751fe282019-02-09 22:22:28 +00005694 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
John McCall7f416cc2015-09-08 08:05:57 +00005695 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005696 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005697 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5698 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005699 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005700 // Store array size.
5701 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00005702 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005703 llvm::Value *Size = CGF.Builder.CreateIntCast(
5704 CGF.getVLASize(
5705 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005706 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005707 CGF.SizeTy, /*isSigned=*/false);
5708 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5709 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005710 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005711 }
5712
5713 // 2. Emit reduce_func().
James Y Knight9871db02019-02-05 16:42:33 +00005714 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00005715 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
5716 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005717
5718 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005719 std::string Name = getName({"reduction"});
5720 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005721
5722 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5723 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005724 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5725 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5726 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5727 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005728 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005729 llvm::Value *Args[] = {
5730 IdentTLoc, // ident_t *<loc>
5731 ThreadId, // i32 <gtid>
5732 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5733 ReductionArrayTySize, // size_type sizeof(RedList)
5734 RL, // void *RedList
5735 ReductionFn, // void (*) (void *, void *) <reduce_func>
5736 Lock // kmp_critical_name *&<lock>
5737 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005738 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005739 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5740 : OMPRTL__kmpc_reduce),
5741 Args);
5742
5743 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005744 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5745 llvm::SwitchInst *SwInst =
5746 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005747
5748 // 6. Build case 1:
5749 // ...
5750 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5751 // ...
5752 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5753 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005754 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005755 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5756 CGF.EmitBlock(Case1BB);
5757
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005758 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5759 llvm::Value *EndArgs[] = {
5760 IdentTLoc, // ident_t *<loc>
5761 ThreadId, // i32 <gtid>
5762 Lock // kmp_critical_name *&<lock>
5763 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005764 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5765 CodeGenFunction &CGF, PrePostActionTy &Action) {
5766 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005767 auto IPriv = Privates.begin();
5768 auto ILHS = LHSExprs.begin();
5769 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005770 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005771 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5772 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005773 ++IPriv;
5774 ++ILHS;
5775 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005776 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005777 };
5778 RegionCodeGenTy RCG(CodeGen);
5779 CommonActionTy Action(
5780 nullptr, llvm::None,
5781 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5782 : OMPRTL__kmpc_end_reduce),
5783 EndArgs);
5784 RCG.setAction(Action);
5785 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005786
5787 CGF.EmitBranch(DefaultBB);
5788
5789 // 7. Build case 2:
5790 // ...
5791 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5792 // ...
5793 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005794 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005795 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5796 CGF.EmitBlock(Case2BB);
5797
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005798 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5799 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005800 auto ILHS = LHSExprs.begin();
5801 auto IRHS = RHSExprs.begin();
5802 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005803 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005804 const Expr *XExpr = nullptr;
5805 const Expr *EExpr = nullptr;
5806 const Expr *UpExpr = nullptr;
5807 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005808 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005809 if (BO->getOpcode() == BO_Assign) {
5810 XExpr = BO->getLHS();
5811 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005812 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005813 }
5814 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005815 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005816 if (RHSExpr) {
5817 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005818 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005819 RHSExpr->IgnoreParenImpCasts())) {
5820 // If this is a conditional operator, analyze its condition for
5821 // min/max reduction operator.
5822 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005823 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005824 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005825 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5826 EExpr = BORHS->getRHS();
5827 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005828 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005829 }
5830 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005831 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005832 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005833 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5834 const Expr *EExpr, const Expr *UpExpr) {
5835 LValue X = CGF.EmitLValue(XExpr);
5836 RValue E;
5837 if (EExpr)
5838 E = CGF.EmitAnyExpr(EExpr);
5839 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005840 X, E, BO, /*IsXLHSInRHSPart=*/true,
5841 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005842 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005843 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5844 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005845 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005846 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5847 CGF.emitOMPSimpleStore(
5848 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5849 VD->getType().getNonReferenceType(), Loc);
5850 return LHSTemp;
5851 });
5852 (void)PrivateScope.Privatize();
5853 return CGF.EmitAnyExpr(UpExpr);
5854 });
5855 };
5856 if ((*IPriv)->getType()->isArrayType()) {
5857 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005858 const auto *RHSVar =
5859 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005860 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5861 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005862 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005863 // Emit atomic reduction for array subscript or single variable.
5864 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005865 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005866 } else {
5867 // Emit as a critical region.
5868 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005869 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005870 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005871 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005872 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005873 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005874 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5875 Action.Enter(CGF);
5876 emitReductionCombiner(CGF, E);
5877 },
5878 Loc);
5879 };
5880 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005881 const auto *LHSVar =
5882 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5883 const auto *RHSVar =
5884 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005885 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5886 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005887 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005888 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005889 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005890 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005891 ++ILHS;
5892 ++IRHS;
5893 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005894 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005895 };
5896 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5897 if (!WithNowait) {
5898 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5899 llvm::Value *EndArgs[] = {
5900 IdentTLoc, // ident_t *<loc>
5901 ThreadId, // i32 <gtid>
5902 Lock // kmp_critical_name *&<lock>
5903 };
5904 CommonActionTy Action(nullptr, llvm::None,
5905 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5906 EndArgs);
5907 AtomicRCG.setAction(Action);
5908 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005909 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005910 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005911 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005912
5913 CGF.EmitBranch(DefaultBB);
5914 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5915}
5916
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005917/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005918/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5919static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5920 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005921 SmallString<256> Buffer;
5922 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005923 const clang::DeclRefExpr *DE;
5924 const VarDecl *D = ::getBaseDecl(Ref, DE);
5925 if (!D)
5926 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5927 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005928 std::string Name = CGM.getOpenMPRuntime().getName(
5929 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5930 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005931 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005932 return Out.str();
5933}
5934
5935/// Emits reduction initializer function:
5936/// \code
5937/// void @.red_init(void* %arg) {
5938/// %0 = bitcast void* %arg to <type>*
5939/// store <type> <init>, <type>* %0
5940/// ret void
5941/// }
5942/// \endcode
5943static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5944 SourceLocation Loc,
5945 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005946 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005947 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005948 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5949 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005950 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005951 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005952 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005953 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005954 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005955 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005956 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005957 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005958 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005959 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005960 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005961 Address PrivateAddr = CGF.EmitLoadOfPointer(
5962 CGF.GetAddrOfLocalVar(&Param),
5963 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5964 llvm::Value *Size = nullptr;
5965 // If the size of the reduction item is non-constant, load it from global
5966 // threadprivate variable.
5967 if (RCG.getSizes(N).second) {
5968 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5969 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005970 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005971 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5972 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005973 }
5974 RCG.emitAggregateType(CGF, N, Size);
5975 LValue SharedLVal;
5976 // If initializer uses initializer from declare reduction construct, emit a
5977 // pointer to the address of the original reduction item (reuired by reduction
5978 // initializer)
5979 if (RCG.usesReductionInitializer(N)) {
5980 Address SharedAddr =
5981 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5982 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005983 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005984 SharedAddr = CGF.EmitLoadOfPointer(
5985 SharedAddr,
5986 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005987 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5988 } else {
5989 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5990 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5991 CGM.getContext().VoidPtrTy);
5992 }
5993 // Emit the initializer:
5994 // %0 = bitcast void* %arg to <type>*
5995 // store <type> <init>, <type>* %0
5996 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5997 [](CodeGenFunction &) { return false; });
5998 CGF.FinishFunction();
5999 return Fn;
6000}
6001
6002/// Emits reduction combiner function:
6003/// \code
6004/// void @.red_comb(void* %arg0, void* %arg1) {
6005/// %lhs = bitcast void* %arg0 to <type>*
6006/// %rhs = bitcast void* %arg1 to <type>*
6007/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
6008/// store <type> %2, <type>* %lhs
6009/// ret void
6010/// }
6011/// \endcode
6012static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
6013 SourceLocation Loc,
6014 ReductionCodeGen &RCG, unsigned N,
6015 const Expr *ReductionOp,
6016 const Expr *LHS, const Expr *RHS,
6017 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006018 ASTContext &C = CGM.getContext();
6019 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
6020 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006021 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006022 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
6023 C.VoidPtrTy, ImplicitParamDecl::Other);
6024 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
6025 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006026 Args.emplace_back(&ParamInOut);
6027 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006028 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006029 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006030 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00006031 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006032 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006033 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00006034 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00006035 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006036 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006037 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006038 llvm::Value *Size = nullptr;
6039 // If the size of the reduction item is non-constant, load it from global
6040 // threadprivate variable.
6041 if (RCG.getSizes(N).second) {
6042 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6043 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006044 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006045 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6046 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006047 }
6048 RCG.emitAggregateType(CGF, N, Size);
6049 // Remap lhs and rhs variables to the addresses of the function arguments.
6050 // %lhs = bitcast void* %arg0 to <type>*
6051 // %rhs = bitcast void* %arg1 to <type>*
6052 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006053 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006054 // Pull out the pointer to the variable.
6055 Address PtrAddr = CGF.EmitLoadOfPointer(
6056 CGF.GetAddrOfLocalVar(&ParamInOut),
6057 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6058 return CGF.Builder.CreateElementBitCast(
6059 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
6060 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006061 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006062 // Pull out the pointer to the variable.
6063 Address PtrAddr = CGF.EmitLoadOfPointer(
6064 CGF.GetAddrOfLocalVar(&ParamIn),
6065 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6066 return CGF.Builder.CreateElementBitCast(
6067 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
6068 });
6069 PrivateScope.Privatize();
6070 // Emit the combiner body:
6071 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
6072 // store <type> %2, <type>* %lhs
6073 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
6074 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
6075 cast<DeclRefExpr>(RHS));
6076 CGF.FinishFunction();
6077 return Fn;
6078}
6079
6080/// Emits reduction finalizer function:
6081/// \code
6082/// void @.red_fini(void* %arg) {
6083/// %0 = bitcast void* %arg to <type>*
6084/// <destroy>(<type>* %0)
6085/// ret void
6086/// }
6087/// \endcode
6088static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
6089 SourceLocation Loc,
6090 ReductionCodeGen &RCG, unsigned N) {
6091 if (!RCG.needCleanups(N))
6092 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006093 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006094 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006095 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
6096 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006097 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006098 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006099 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006100 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00006101 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006102 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006103 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00006104 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00006105 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006106 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006107 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006108 Address PrivateAddr = CGF.EmitLoadOfPointer(
6109 CGF.GetAddrOfLocalVar(&Param),
6110 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6111 llvm::Value *Size = nullptr;
6112 // If the size of the reduction item is non-constant, load it from global
6113 // threadprivate variable.
6114 if (RCG.getSizes(N).second) {
6115 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6116 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006117 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006118 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6119 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006120 }
6121 RCG.emitAggregateType(CGF, N, Size);
6122 // Emit the finalizer body:
6123 // <destroy>(<type>* %0)
6124 RCG.emitCleanups(CGF, N, PrivateAddr);
6125 CGF.FinishFunction();
6126 return Fn;
6127}
6128
6129llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
6130 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
6131 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
6132 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
6133 return nullptr;
6134
6135 // Build typedef struct:
6136 // kmp_task_red_input {
6137 // void *reduce_shar; // shared reduction item
6138 // size_t reduce_size; // size of data item
6139 // void *reduce_init; // data initialization routine
6140 // void *reduce_fini; // data finalization routine
6141 // void *reduce_comb; // data combiner routine
6142 // kmp_task_red_flags_t flags; // flags for additional info from compiler
6143 // } kmp_task_red_input_t;
6144 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006145 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006146 RD->startDefinition();
6147 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6148 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
6149 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6150 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6151 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6152 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6153 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6154 RD->completeDefinition();
6155 QualType RDType = C.getRecordType(RD);
6156 unsigned Size = Data.ReductionVars.size();
6157 llvm::APInt ArraySize(/*numBits=*/64, Size);
6158 QualType ArrayRDType = C.getConstantArrayType(
6159 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6160 // kmp_task_red_input_t .rd_input.[Size];
6161 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6162 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6163 Data.ReductionOps);
6164 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6165 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6166 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6167 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6168 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6169 TaskRedInput.getPointer(), Idxs,
6170 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6171 ".rd_input.gep.");
6172 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6173 // ElemLVal.reduce_shar = &Shareds[Cnt];
6174 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6175 RCG.emitSharedLValue(CGF, Cnt);
6176 llvm::Value *CastedShared =
6177 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6178 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6179 RCG.emitAggregateType(CGF, Cnt);
6180 llvm::Value *SizeValInChars;
6181 llvm::Value *SizeVal;
6182 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6183 // We use delayed creation/initialization for VLAs, array sections and
6184 // custom reduction initializations. It is required because runtime does not
6185 // provide the way to pass the sizes of VLAs/array sections to
6186 // initializer/combiner/finalizer functions and does not pass the pointer to
6187 // original reduction item to the initializer. Instead threadprivate global
6188 // variables are used to store these values and use them in the functions.
6189 bool DelayedCreation = !!SizeVal;
6190 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6191 /*isSigned=*/false);
6192 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6193 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6194 // ElemLVal.reduce_init = init;
6195 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6196 llvm::Value *InitAddr =
6197 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6198 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6199 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6200 // ElemLVal.reduce_fini = fini;
6201 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6202 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6203 llvm::Value *FiniAddr = Fini
6204 ? CGF.EmitCastToVoidPtr(Fini)
6205 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6206 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6207 // ElemLVal.reduce_comb = comb;
6208 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6209 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6210 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6211 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6212 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6213 // ElemLVal.flags = 0;
6214 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6215 if (DelayedCreation) {
6216 CGF.EmitStoreOfScalar(
6217 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6218 FlagsLVal);
6219 } else
6220 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6221 }
6222 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6223 // *data);
6224 llvm::Value *Args[] = {
6225 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6226 /*isSigned=*/true),
6227 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6228 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6229 CGM.VoidPtrTy)};
6230 return CGF.EmitRuntimeCall(
6231 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6232}
6233
6234void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6235 SourceLocation Loc,
6236 ReductionCodeGen &RCG,
6237 unsigned N) {
6238 auto Sizes = RCG.getSizes(N);
6239 // Emit threadprivate global variable if the type is non-constant
6240 // (Sizes.second = nullptr).
6241 if (Sizes.second) {
6242 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6243 /*isSigned=*/false);
6244 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6245 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006246 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006247 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6248 }
6249 // Store address of the original reduction item if custom initializer is used.
6250 if (RCG.usesReductionInitializer(N)) {
6251 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6252 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006253 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006254 CGF.Builder.CreateStore(
6255 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6256 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6257 SharedAddr, /*IsVolatile=*/false);
6258 }
6259}
6260
6261Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6262 SourceLocation Loc,
6263 llvm::Value *ReductionsPtr,
6264 LValue SharedLVal) {
6265 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6266 // *d);
6267 llvm::Value *Args[] = {
6268 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6269 /*isSigned=*/true),
6270 ReductionsPtr,
6271 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6272 CGM.VoidPtrTy)};
6273 return Address(
6274 CGF.EmitRuntimeCall(
6275 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6276 SharedLVal.getAlignment());
6277}
6278
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006279void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6280 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006281 if (!CGF.HaveInsertPoint())
6282 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006283 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6284 // global_tid);
6285 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6286 // Ignore return result until untied tasks are supported.
6287 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006288 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6289 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006290}
6291
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006292void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006293 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006294 const RegionCodeGenTy &CodeGen,
6295 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006296 if (!CGF.HaveInsertPoint())
6297 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006298 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006299 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006300}
6301
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006302namespace {
6303enum RTCancelKind {
6304 CancelNoreq = 0,
6305 CancelParallel = 1,
6306 CancelLoop = 2,
6307 CancelSections = 3,
6308 CancelTaskgroup = 4
6309};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006310} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006311
6312static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6313 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006314 if (CancelRegion == OMPD_parallel)
6315 CancelKind = CancelParallel;
6316 else if (CancelRegion == OMPD_for)
6317 CancelKind = CancelLoop;
6318 else if (CancelRegion == OMPD_sections)
6319 CancelKind = CancelSections;
6320 else {
6321 assert(CancelRegion == OMPD_taskgroup);
6322 CancelKind = CancelTaskgroup;
6323 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006324 return CancelKind;
6325}
6326
6327void CGOpenMPRuntime::emitCancellationPointCall(
6328 CodeGenFunction &CGF, SourceLocation Loc,
6329 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006330 if (!CGF.HaveInsertPoint())
6331 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006332 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6333 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006334 if (auto *OMPRegionInfo =
6335 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006336 // For 'cancellation point taskgroup', the task region info may not have a
6337 // cancel. This may instead happen in another adjacent task.
6338 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006339 llvm::Value *Args[] = {
6340 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6341 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006342 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006343 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006344 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6345 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006346 // exit from construct;
6347 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006348 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6349 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6350 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006351 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6352 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006353 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006354 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006355 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006356 CGF.EmitBranchThroughCleanup(CancelDest);
6357 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6358 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006359 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006360}
6361
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006362void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006363 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006364 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006365 if (!CGF.HaveInsertPoint())
6366 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006367 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6368 // kmp_int32 cncl_kind);
6369 if (auto *OMPRegionInfo =
6370 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006371 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6372 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006373 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006374 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006375 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006376 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6377 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006378 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006379 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006380 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006381 // exit from construct;
6382 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006383 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6384 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6385 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006386 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6387 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006388 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006389 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006390 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6391 CGF.EmitBranchThroughCleanup(CancelDest);
6392 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6393 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006394 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006395 emitOMPIfClause(CGF, IfCond, ThenGen,
6396 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006397 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006398 RegionCodeGenTy ThenRCG(ThenGen);
6399 ThenRCG(CGF);
6400 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006401 }
6402}
Samuel Antaobed3c462015-10-02 16:14:20 +00006403
Samuel Antaoee8fb302016-01-06 13:42:12 +00006404void CGOpenMPRuntime::emitTargetOutlinedFunction(
6405 const OMPExecutableDirective &D, StringRef ParentName,
6406 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006407 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006408 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006409 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6410 IsOffloadEntry, CodeGen);
6411}
6412
6413void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6414 const OMPExecutableDirective &D, StringRef ParentName,
6415 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6416 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006417 // Create a unique name for the entry function using the source location
6418 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006419 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006420 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006421 //
6422 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006423 // mangled name of the function that encloses the target region and BB is the
6424 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006425
6426 unsigned DeviceID;
6427 unsigned FileID;
6428 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006429 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006430 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006431 SmallString<64> EntryFnName;
6432 {
6433 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006434 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6435 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006436 }
6437
Alexey Bataev475a7442018-01-12 19:39:11 +00006438 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006439
Samuel Antaobed3c462015-10-02 16:14:20 +00006440 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006441 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006442 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006443
Samuel Antao6d004262016-06-16 18:39:34 +00006444 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006445
6446 // If this target outline function is not an offload entry, we don't need to
6447 // register it.
6448 if (!IsOffloadEntry)
6449 return;
6450
6451 // The target region ID is used by the runtime library to identify the current
6452 // target region, so it only has to be unique and not necessarily point to
6453 // anything. It could be the pointer to the outlined function that implements
6454 // the target region, but we aren't using that so that the compiler doesn't
6455 // need to keep that, and could therefore inline the host function if proven
6456 // worthwhile during optimization. In the other hand, if emitting code for the
6457 // device, the ID has to be the function address so that it can retrieved from
6458 // the offloading entry and launched by the runtime library. We also mark the
6459 // outlined function to have external linkage in case we are emitting code for
6460 // the device, because these functions will be entry points to the device.
6461
6462 if (CGM.getLangOpts().OpenMPIsDevice) {
6463 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006464 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006465 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006466 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006467 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006468 OutlinedFnID = new llvm::GlobalVariable(
6469 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006470 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006471 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006472 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006473
6474 // Register the information for the entry associated with this target region.
6475 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006476 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006477 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006478}
6479
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006480/// discard all CompoundStmts intervening between two constructs
6481static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006482 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006483 Body = CS->body_front();
6484
6485 return Body;
6486}
6487
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006488/// Emit the number of teams for a target directive. Inspect the num_teams
6489/// clause associated with a teams construct combined or closely nested
6490/// with the target directive.
6491///
6492/// Emit a team of size one for directives such as 'target parallel' that
6493/// have no associated teams construct.
6494///
6495/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006496static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006497emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6498 CodeGenFunction &CGF,
6499 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006500 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6501 "teams directive expected to be "
6502 "emitted only for the host!");
6503
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006504 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006505
6506 // If the target directive is combined with a teams directive:
6507 // Return the value in the num_teams clause, if any.
6508 // Otherwise, return 0 to denote the runtime default.
6509 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6510 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6511 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006512 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6513 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006514 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6515 /*IsSigned=*/true);
6516 }
6517
6518 // The default value is 0.
6519 return Bld.getInt32(0);
6520 }
6521
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006522 // If the target directive is combined with a parallel directive but not a
6523 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006524 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6525 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006526
6527 // If the current target region has a teams region enclosed, we need to get
6528 // the number of teams to pass to the runtime function call. This is done
6529 // by generating the expression in a inlined region. This is required because
6530 // the expression is captured in the enclosing target environment when the
6531 // teams directive is not combined with target.
6532
Alexey Bataev475a7442018-01-12 19:39:11 +00006533 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006534
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006535 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006536 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006537 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006538 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006539 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6540 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6541 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6542 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6543 /*IsSigned=*/true);
6544 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006545
Alexey Bataev50a1c782017-12-01 21:31:08 +00006546 // If we have an enclosed teams directive but no num_teams clause we use
6547 // the default value 0.
6548 return Bld.getInt32(0);
6549 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006550 }
6551
6552 // No teams associated with the directive.
6553 return nullptr;
6554}
6555
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006556/// Emit the number of threads for a target directive. Inspect the
6557/// thread_limit clause associated with a teams construct combined or closely
6558/// nested with the target directive.
6559///
6560/// Emit the num_threads clause for directives such as 'target parallel' that
6561/// have no associated teams construct.
6562///
6563/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006564static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006565emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6566 CodeGenFunction &CGF,
6567 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006568 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6569 "teams directive expected to be "
6570 "emitted only for the host!");
6571
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006572 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006573
6574 //
6575 // If the target directive is combined with a teams directive:
6576 // Return the value in the thread_limit clause, if any.
6577 //
6578 // If the target directive is combined with a parallel directive:
6579 // Return the value in the num_threads clause, if any.
6580 //
6581 // If both clauses are set, select the minimum of the two.
6582 //
6583 // If neither teams or parallel combined directives set the number of threads
6584 // in a team, return 0 to denote the runtime default.
6585 //
6586 // If this is not a teams directive return nullptr.
6587
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006588 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6589 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006590 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6591 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006592 llvm::Value *ThreadLimitVal = nullptr;
6593
6594 if (const auto *ThreadLimitClause =
6595 D.getSingleClause<OMPThreadLimitClause>()) {
6596 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006597 llvm::Value *ThreadLimit =
6598 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6599 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006600 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6601 /*IsSigned=*/true);
6602 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006603
6604 if (const auto *NumThreadsClause =
6605 D.getSingleClause<OMPNumThreadsClause>()) {
6606 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6607 llvm::Value *NumThreads =
6608 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6609 /*IgnoreResultAssign*/ true);
6610 NumThreadsVal =
6611 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6612 }
6613
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006614 // Select the lesser of thread_limit and num_threads.
6615 if (NumThreadsVal)
6616 ThreadLimitVal = ThreadLimitVal
6617 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6618 ThreadLimitVal),
6619 NumThreadsVal, ThreadLimitVal)
6620 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006621
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006622 // Set default value passed to the runtime if either teams or a target
6623 // parallel type directive is found but no clause is specified.
6624 if (!ThreadLimitVal)
6625 ThreadLimitVal = DefaultThreadLimitVal;
6626
6627 return ThreadLimitVal;
6628 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006629
Samuel Antaob68e2db2016-03-03 16:20:23 +00006630 // If the current target region has a teams region enclosed, we need to get
6631 // the thread limit to pass to the runtime function call. This is done
6632 // by generating the expression in a inlined region. This is required because
6633 // the expression is captured in the enclosing target environment when the
6634 // teams directive is not combined with target.
6635
Alexey Bataev475a7442018-01-12 19:39:11 +00006636 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006637
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006638 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006639 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006640 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006641 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006642 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6643 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6644 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6645 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6646 /*IsSigned=*/true);
6647 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006648
Alexey Bataev50a1c782017-12-01 21:31:08 +00006649 // If we have an enclosed teams directive but no thread_limit clause we
6650 // use the default value 0.
6651 return CGF.Builder.getInt32(0);
6652 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006653 }
6654
6655 // No teams associated with the directive.
6656 return nullptr;
6657}
6658
Samuel Antao86ace552016-04-27 22:40:57 +00006659namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006660LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6661
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006662// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006663// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6664// It provides a convenient interface to obtain the information and generate
6665// code for that information.
6666class MappableExprsHandler {
6667public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006668 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006669 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006670 enum OpenMPOffloadMappingFlags : uint64_t {
6671 /// No flags
6672 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006673 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006674 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006675 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006676 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006677 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006678 /// if it was already mapped before.
6679 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006680 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006681 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006682 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006683 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006684 /// pointer and the pointee should be mapped.
6685 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006686 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006687 /// passed to the target kernel as an argument.
6688 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006689 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006690 /// in the current position for the data being mapped. Used when we have the
6691 /// use_device_ptr clause.
6692 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006693 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006694 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006695 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006696 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006697 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006698 /// Implicit map
6699 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006700 /// The 16 MSBs of the flags indicate whether the entry is member of some
6701 /// struct/class.
6702 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6703 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006704 };
6705
Samuel Antaocc10b852016-07-28 14:23:26 +00006706 /// Class that associates information with a base pointer to be passed to the
6707 /// runtime library.
6708 class BasePointerInfo {
6709 /// The base pointer.
6710 llvm::Value *Ptr = nullptr;
6711 /// The base declaration that refers to this device pointer, or null if
6712 /// there is none.
6713 const ValueDecl *DevPtrDecl = nullptr;
6714
6715 public:
6716 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6717 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6718 llvm::Value *operator*() const { return Ptr; }
6719 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6720 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6721 };
6722
Alexey Bataevb3638132018-07-19 16:34:13 +00006723 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6724 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6725 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6726
6727 /// Map between a struct and the its lowest & highest elements which have been
6728 /// mapped.
6729 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6730 /// HE(FieldIndex, Pointer)}
6731 struct StructRangeInfoTy {
6732 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6733 0, Address::invalid()};
6734 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6735 0, Address::invalid()};
6736 Address Base = Address::invalid();
6737 };
Samuel Antao86ace552016-04-27 22:40:57 +00006738
6739private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006740 /// Kind that defines how a device pointer has to be returned.
6741 struct MapInfo {
6742 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6743 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
Kelvin Lief579432018-12-18 22:18:41 +00006744 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataevb3638132018-07-19 16:34:13 +00006745 bool ReturnDevicePointer = false;
6746 bool IsImplicit = false;
6747
6748 MapInfo() = default;
6749 MapInfo(
6750 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Kelvin Lief579432018-12-18 22:18:41 +00006751 OpenMPMapClauseKind MapType,
6752 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00006753 bool ReturnDevicePointer, bool IsImplicit)
Kelvin Lief579432018-12-18 22:18:41 +00006754 : Components(Components), MapType(MapType), MapModifiers(MapModifiers),
Alexey Bataevb3638132018-07-19 16:34:13 +00006755 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6756 };
6757
6758 /// If use_device_ptr is used on a pointer which is a struct member and there
6759 /// is no map information about it, then emission of that entry is deferred
6760 /// until the whole struct has been processed.
6761 struct DeferredDevicePtrEntryTy {
6762 const Expr *IE = nullptr;
6763 const ValueDecl *VD = nullptr;
6764
6765 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6766 : IE(IE), VD(VD) {}
6767 };
6768
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006769 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006770 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006771
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006772 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006773 CodeGenFunction &CGF;
6774
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006775 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006776 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6777
Samuel Antao6890b092016-07-28 14:25:09 +00006778 /// Map between device pointer declarations and their expression components.
6779 /// The key value for declarations in 'this' is null.
6780 llvm::DenseMap<
6781 const ValueDecl *,
6782 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6783 DevPointersMap;
6784
Samuel Antao86ace552016-04-27 22:40:57 +00006785 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006786 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006787
6788 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006789 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006790 ExprTy = RefTy->getPointeeType().getCanonicalType();
6791
6792 // Given that an array section is considered a built-in type, we need to
6793 // do the calculation based on the length of the section instead of relying
6794 // on CGF.getTypeSize(E->getType()).
6795 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6796 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6797 OAE->getBase()->IgnoreParenImpCasts())
6798 .getCanonicalType();
6799
6800 // If there is no length associated with the expression, that means we
6801 // are using the whole length of the base.
6802 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6803 return CGF.getTypeSize(BaseTy);
6804
6805 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006806 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006807 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006808 } else {
6809 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006810 assert(ATy && "Expecting array type if not a pointer type.");
6811 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6812 }
6813
6814 // If we don't have a length at this point, that is because we have an
6815 // array section with a single element.
6816 if (!OAE->getLength())
6817 return ElemSize;
6818
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006819 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006820 LengthVal =
6821 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6822 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6823 }
6824 return CGF.getTypeSize(ExprTy);
6825 }
6826
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006827 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006828 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006829 /// map as the first one of a series of maps that relate to the same map
6830 /// expression.
Kelvin Lief579432018-12-18 22:18:41 +00006831 OpenMPOffloadMappingFlags getMapTypeBits(
6832 OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
6833 bool IsImplicit, bool AddPtrFlag, bool AddIsTargetParamFlag) const {
Alexey Bataevb3638132018-07-19 16:34:13 +00006834 OpenMPOffloadMappingFlags Bits =
6835 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006836 switch (MapType) {
6837 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006838 case OMPC_MAP_release:
6839 // alloc and release is the default behavior in the runtime library, i.e.
6840 // if we don't pass any bits alloc/release that is what the runtime is
6841 // going to do. Therefore, we don't need to signal anything for these two
6842 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006843 break;
6844 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006845 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006846 break;
6847 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006848 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006849 break;
6850 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006851 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006852 break;
6853 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006854 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006855 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006856 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006857 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006858 }
6859 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006860 Bits |= OMP_MAP_PTR_AND_OBJ;
6861 if (AddIsTargetParamFlag)
6862 Bits |= OMP_MAP_TARGET_PARAM;
Kelvin Lief579432018-12-18 22:18:41 +00006863 if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_always)
6864 != MapModifiers.end())
Samuel Antao86ace552016-04-27 22:40:57 +00006865 Bits |= OMP_MAP_ALWAYS;
6866 return Bits;
6867 }
6868
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006869 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006870 /// final array section, is one whose length can't be proved to be one.
6871 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006872 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006873
6874 // It is not an array section and therefore not a unity-size one.
6875 if (!OASE)
6876 return false;
6877
6878 // An array section with no colon always refer to a single element.
6879 if (OASE->getColonLoc().isInvalid())
6880 return false;
6881
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006882 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006883
6884 // If we don't have a length we have to check if the array has size 1
6885 // for this dimension. Also, we should always expect a length if the
6886 // base type is pointer.
6887 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006888 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6889 OASE->getBase()->IgnoreParenImpCasts())
6890 .getCanonicalType();
6891 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006892 return ATy->getSize().getSExtValue() != 1;
6893 // If we don't have a constant dimension length, we have to consider
6894 // the current section as having any size, so it is not necessarily
6895 // unitary. If it happen to be unity size, that's user fault.
6896 return true;
6897 }
6898
6899 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +00006900 Expr::EvalResult Result;
6901 if (!Length->EvaluateAsInt(Result, CGF.getContext()))
Samuel Antao86ace552016-04-27 22:40:57 +00006902 return true; // Can have more that size 1.
6903
Fangrui Song407659a2018-11-30 23:41:18 +00006904 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antao86ace552016-04-27 22:40:57 +00006905 return ConstLength.getSExtValue() != 1;
6906 }
6907
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006908 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006909 /// bits for the provided map type, map modifier, and expression components.
6910 /// \a IsFirstComponent should be set to true if the provided set of
6911 /// components is the first associated with a capture.
6912 void generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00006913 OpenMPMapClauseKind MapType,
6914 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Samuel Antao86ace552016-04-27 22:40:57 +00006915 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006916 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006917 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006918 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006919 bool IsImplicit,
6920 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6921 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006922 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006923 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006924 // base pointer, section pointer, size, flags
6925 // (to add to the ones that come from the map type and modifier).
6926 //
6927 // double d;
6928 // int i[100];
6929 // float *p;
6930 //
6931 // struct S1 {
6932 // int i;
6933 // float f[50];
6934 // }
6935 // struct S2 {
6936 // int i;
6937 // float f[50];
6938 // S1 s;
6939 // double *p;
6940 // struct S2 *ps;
6941 // }
6942 // S2 s;
6943 // S2 *ps;
6944 //
6945 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006946 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006947 //
6948 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006949 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006950 //
6951 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006952 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006953 //
6954 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006955 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006956 //
6957 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006958 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006959 //
6960 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006961 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006962 //
6963 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006964 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006965 //
6966 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006967 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006968 //
6969 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006970 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006971 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006972 // map(to: s.p[:22])
6973 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6974 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6975 // &(s.p), &(s.p[0]), 22*sizeof(double),
6976 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6977 // (*) alloc space for struct members, only this is a target parameter
6978 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6979 // optimizes this entry out, same in the examples below)
6980 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006981 //
6982 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006983 // &s, &(s.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: s.ps->s.i)
6986 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6987 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6988 // &(s.ps), &(s.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(to: s.ps->ps)
6991 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6992 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6993 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006994 //
6995 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006996 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6997 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6998 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6999 // &(s.ps->ps), &(s.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: s.ps->ps->s.f[:22])
7002 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
7003 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
7004 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
7005 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00007006 //
7007 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00007008 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00007009 //
7010 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00007011 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00007012 //
7013 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00007014 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00007015 //
Alexey Bataevb3638132018-07-19 16:34:13 +00007016 // map(from: ps->p)
7017 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00007018 //
Alexey Bataevb3638132018-07-19 16:34:13 +00007019 // map(to: ps->p[:22])
7020 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
7021 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
7022 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00007023 //
7024 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00007025 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00007026 //
Alexey Bataevb3638132018-07-19 16:34:13 +00007027 // map(from: ps->ps->s.i)
7028 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
7029 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
7030 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00007031 //
Alexey Bataevb3638132018-07-19 16:34:13 +00007032 // map(from: ps->ps->ps)
7033 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
7034 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
7035 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00007036 //
7037 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00007038 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
7039 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
7040 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
7041 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00007042 //
Alexey Bataevb3638132018-07-19 16:34:13 +00007043 // map(to: ps->ps->ps->s.f[:22])
7044 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
7045 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
7046 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
7047 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
7048 //
7049 // map(to: s.f[:22]) map(from: s.p[:33])
7050 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
7051 // sizeof(double*) (**), TARGET_PARAM
7052 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
7053 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
7054 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
7055 // (*) allocate contiguous space needed to fit all mapped members even if
7056 // we allocate space for members not mapped (in this example,
7057 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
7058 // them as well because they fall between &s.f[0] and &s.p)
7059 //
7060 // map(from: s.f[:22]) map(to: ps->p[:33])
7061 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
7062 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7063 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
7064 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
7065 // (*) the struct this entry pertains to is the 2nd element in the list of
7066 // arguments, hence MEMBER_OF(2)
7067 //
7068 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
7069 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
7070 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
7071 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
7072 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7073 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
7074 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
7075 // (*) the struct this entry pertains to is the 4th element in the list
7076 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00007077
7078 // Track if the map information being generated is the first for a capture.
7079 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00007080 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00007081
7082 // Scan the components from the base to the complete expression.
7083 auto CI = Components.rbegin();
7084 auto CE = Components.rend();
7085 auto I = CI;
7086
7087 // Track if the map information being generated is the first for a list of
7088 // components.
7089 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007090 Address BP = Address::invalid();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007091 const Expr *AssocExpr = I->getAssociatedExpression();
7092 const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr);
7093 const auto *OASE = dyn_cast<OMPArraySectionExpr>(AssocExpr);
Samuel Antao86ace552016-04-27 22:40:57 +00007094
Patrick Lystere13b1e32019-01-02 19:28:48 +00007095 if (isa<MemberExpr>(AssocExpr)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007096 // The base is the 'this' pointer. The content of the pointer is going
7097 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00007098 BP = CGF.LoadCXXThisAddress();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007099 } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) ||
7100 (OASE &&
7101 isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) {
7102 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007103 } else {
7104 // The base is the reference to the variable.
7105 // BP = &Var.
Patrick Lystere13b1e32019-01-02 19:28:48 +00007106 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00007107 if (const auto *VD =
7108 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
7109 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007110 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007111 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
7112 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007113 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007114 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007115 }
Samuel Antao86ace552016-04-27 22:40:57 +00007116
7117 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00007118 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00007119 // reference. References are ignored for mapping purposes.
7120 QualType Ty =
7121 I->getAssociatedDeclaration()->getType().getNonReferenceType();
7122 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007123 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00007124
7125 // We do not need to generate individual map information for the
7126 // pointer, it can be associated with the combined storage.
7127 ++I;
7128 }
7129 }
7130
Alexey Bataevb3638132018-07-19 16:34:13 +00007131 // Track whether a component of the list should be marked as MEMBER_OF some
7132 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7133 // in a component list should be marked as MEMBER_OF, all subsequent entries
7134 // do not belong to the base struct. E.g.
7135 // struct S2 s;
7136 // s.ps->ps->ps->f[:]
7137 // (1) (2) (3) (4)
7138 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7139 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7140 // is the pointee of ps(2) which is not member of struct s, so it should not
7141 // be marked as such (it is still PTR_AND_OBJ).
7142 // The variable is initialized to false so that PTR_AND_OBJ entries which
7143 // are not struct members are not considered (e.g. array of pointers to
7144 // data).
7145 bool ShouldBeMemberOf = false;
7146
7147 // Variable keeping track of whether or not we have encountered a component
7148 // in the component list which is a member expression. Useful when we have a
7149 // pointer or a final array section, in which case it is the previous
7150 // component in the list which tells us whether we have a member expression.
7151 // E.g. X.f[:]
7152 // While processing the final array section "[:]" it is "f" which tells us
7153 // whether we are dealing with a member of a declared struct.
7154 const MemberExpr *EncounteredME = nullptr;
7155
Samuel Antao86ace552016-04-27 22:40:57 +00007156 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007157 // If the current component is member of a struct (parent struct) mark it.
7158 if (!EncounteredME) {
7159 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
7160 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
7161 // as MEMBER_OF the parent struct.
7162 if (EncounteredME)
7163 ShouldBeMemberOf = true;
7164 }
7165
Samuel Antao86ace552016-04-27 22:40:57 +00007166 auto Next = std::next(I);
7167
7168 // We need to generate the addresses and sizes if this is the last
7169 // component, if the component is a pointer or if it is an array section
7170 // whose length can't be proved to be one. If this is a pointer, it
7171 // becomes the base address for the following components.
7172
7173 // A final array section, is one whose length can't be proved to be one.
7174 bool IsFinalArraySection =
7175 isFinalArraySectionExpression(I->getAssociatedExpression());
7176
7177 // Get information on whether the element is a pointer. Have to do a
7178 // special treatment for array sections given that they are built-in
7179 // types.
7180 const auto *OASE =
7181 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7182 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007183 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7184 .getCanonicalType()
7185 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007186 I->getAssociatedExpression()->getType()->isAnyPointerType();
7187
7188 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007189 // If this is not the last component, we expect the pointer to be
7190 // associated with an array expression or member expression.
7191 assert((Next == CE ||
7192 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7193 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7194 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7195 "Unexpected expression");
7196
Alexey Bataevb3638132018-07-19 16:34:13 +00007197 Address LB =
7198 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007199
Alexey Bataevb3638132018-07-19 16:34:13 +00007200 // If this component is a pointer inside the base struct then we don't
7201 // need to create any entry for it - it will be combined with the object
7202 // it is pointing to into a single PTR_AND_OBJ entry.
7203 bool IsMemberPointer =
7204 IsPointer && EncounteredME &&
7205 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7206 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007207 if (!OverlappedElements.empty()) {
7208 // Handle base element with the info for overlapped elements.
7209 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7210 assert(Next == CE &&
7211 "Expected last element for the overlapped elements.");
7212 assert(!IsPointer &&
7213 "Unexpected base element with the pointer type.");
7214 // Mark the whole struct as the struct that requires allocation on the
7215 // device.
7216 PartialStruct.LowestElem = {0, LB};
7217 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7218 I->getAssociatedExpression()->getType());
7219 Address HB = CGF.Builder.CreateConstGEP(
7220 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7221 CGF.VoidPtrTy),
James Y Knight751fe282019-02-09 22:22:28 +00007222 TypeSize.getQuantity() - 1);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007223 PartialStruct.HighestElem = {
7224 std::numeric_limits<decltype(
7225 PartialStruct.HighestElem.first)>::max(),
7226 HB};
7227 PartialStruct.Base = BP;
7228 // Emit data for non-overlapped data.
7229 OpenMPOffloadMappingFlags Flags =
7230 OMP_MAP_MEMBER_OF |
Kelvin Lief579432018-12-18 22:18:41 +00007231 getMapTypeBits(MapType, MapModifiers, IsImplicit,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007232 /*AddPtrFlag=*/false,
7233 /*AddIsTargetParamFlag=*/false);
7234 LB = BP;
7235 llvm::Value *Size = nullptr;
7236 // Do bitcopy of all non-overlapped structure elements.
7237 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7238 Component : OverlappedElements) {
7239 Address ComponentLB = Address::invalid();
7240 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7241 Component) {
7242 if (MC.getAssociatedDeclaration()) {
7243 ComponentLB =
7244 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7245 .getAddress();
7246 Size = CGF.Builder.CreatePtrDiff(
7247 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7248 CGF.EmitCastToVoidPtr(LB.getPointer()));
7249 break;
7250 }
7251 }
7252 BasePointers.push_back(BP.getPointer());
7253 Pointers.push_back(LB.getPointer());
7254 Sizes.push_back(Size);
7255 Types.push_back(Flags);
James Y Knight751fe282019-02-09 22:22:28 +00007256 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007257 }
7258 BasePointers.push_back(BP.getPointer());
7259 Pointers.push_back(LB.getPointer());
7260 Size = CGF.Builder.CreatePtrDiff(
7261 CGF.EmitCastToVoidPtr(
James Y Knight751fe282019-02-09 22:22:28 +00007262 CGF.Builder.CreateConstGEP(HB, 1).getPointer()),
Alexey Bataeve82445f2018-09-20 13:54:02 +00007263 CGF.EmitCastToVoidPtr(LB.getPointer()));
7264 Sizes.push_back(Size);
7265 Types.push_back(Flags);
7266 break;
7267 }
7268 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007269 if (!IsMemberPointer) {
7270 BasePointers.push_back(BP.getPointer());
7271 Pointers.push_back(LB.getPointer());
7272 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007273
Alexey Bataevb3638132018-07-19 16:34:13 +00007274 // We need to add a pointer flag for each map that comes from the
7275 // same expression except for the first one. We also need to signal
7276 // this map is the first one that relates with the current capture
7277 // (there is a set of entries for each capture).
7278 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
Kelvin Lief579432018-12-18 22:18:41 +00007279 MapType, MapModifiers, IsImplicit,
Alexey Bataevb3638132018-07-19 16:34:13 +00007280 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7281
7282 if (!IsExpressionFirstInfo) {
7283 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7284 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7285 if (IsPointer)
7286 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7287 OMP_MAP_DELETE);
7288
7289 if (ShouldBeMemberOf) {
7290 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7291 // should be later updated with the correct value of MEMBER_OF.
7292 Flags |= OMP_MAP_MEMBER_OF;
7293 // From now on, all subsequent PTR_AND_OBJ entries should not be
7294 // marked as MEMBER_OF.
7295 ShouldBeMemberOf = false;
7296 }
7297 }
7298
7299 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007300 }
7301
Alexey Bataevb3638132018-07-19 16:34:13 +00007302 // If we have encountered a member expression so far, keep track of the
7303 // mapped member. If the parent is "*this", then the value declaration
7304 // is nullptr.
7305 if (EncounteredME) {
7306 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7307 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007308
Alexey Bataevb3638132018-07-19 16:34:13 +00007309 // Update info about the lowest and highest elements for this struct
7310 if (!PartialStruct.Base.isValid()) {
7311 PartialStruct.LowestElem = {FieldIndex, LB};
7312 PartialStruct.HighestElem = {FieldIndex, LB};
7313 PartialStruct.Base = BP;
7314 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7315 PartialStruct.LowestElem = {FieldIndex, LB};
7316 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7317 PartialStruct.HighestElem = {FieldIndex, LB};
7318 }
7319 }
Samuel Antao86ace552016-04-27 22:40:57 +00007320
7321 // If we have a final array section, we are done with this expression.
7322 if (IsFinalArraySection)
7323 break;
7324
7325 // The pointer becomes the base for the next element.
7326 if (Next != CE)
7327 BP = LB;
7328
7329 IsExpressionFirstInfo = false;
7330 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007331 }
7332 }
7333 }
7334
Alexey Bataevb3638132018-07-19 16:34:13 +00007335 /// Return the adjusted map modifiers if the declaration a capture refers to
7336 /// appears in a first-private clause. This is expected to be used only with
7337 /// directives that start with 'target'.
7338 MappableExprsHandler::OpenMPOffloadMappingFlags
7339 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7340 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7341
7342 // A first private variable captured by reference will use only the
7343 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7344 // declaration is known as first-private in this handler.
Alexey Bataev1af5bd52019-03-05 17:47:18 +00007345 if (FirstPrivateDecls.count(Cap.getCapturedVar())) {
7346 if (Cap.getCapturedVar()->getType().isConstant(CGF.getContext()) &&
7347 Cap.getCaptureKind() == CapturedStmt::VCK_ByRef)
7348 return MappableExprsHandler::OMP_MAP_ALWAYS |
7349 MappableExprsHandler::OMP_MAP_TO;
Alexey Bataevc2b831f2019-04-02 16:03:40 +00007350 if (Cap.getCapturedVar()->getType()->isAnyPointerType())
7351 return MappableExprsHandler::OMP_MAP_TO |
7352 MappableExprsHandler::OMP_MAP_PTR_AND_OBJ;
Alexey Bataevb3638132018-07-19 16:34:13 +00007353 return MappableExprsHandler::OMP_MAP_PRIVATE |
7354 MappableExprsHandler::OMP_MAP_TO;
Alexey Bataev1af5bd52019-03-05 17:47:18 +00007355 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007356 return MappableExprsHandler::OMP_MAP_TO |
7357 MappableExprsHandler::OMP_MAP_FROM;
7358 }
7359
7360 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7361 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7362 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7363 << 48);
7364 }
7365
7366 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7367 OpenMPOffloadMappingFlags MemberOfFlag) {
7368 // If the entry is PTR_AND_OBJ but has not been marked with the special
7369 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7370 // marked as MEMBER_OF.
7371 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7372 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7373 return;
7374
7375 // Reset the placeholder value to prepare the flag for the assignment of the
7376 // proper MEMBER_OF value.
7377 Flags &= ~OMP_MAP_MEMBER_OF;
7378 Flags |= MemberOfFlag;
7379 }
7380
Alexey Bataeve82445f2018-09-20 13:54:02 +00007381 void getPlainLayout(const CXXRecordDecl *RD,
7382 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7383 bool AsBase) const {
7384 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7385
7386 llvm::StructType *St =
7387 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7388
7389 unsigned NumElements = St->getNumElements();
7390 llvm::SmallVector<
7391 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7392 RecordLayout(NumElements);
7393
7394 // Fill bases.
7395 for (const auto &I : RD->bases()) {
7396 if (I.isVirtual())
7397 continue;
7398 const auto *Base = I.getType()->getAsCXXRecordDecl();
7399 // Ignore empty bases.
7400 if (Base->isEmpty() || CGF.getContext()
7401 .getASTRecordLayout(Base)
7402 .getNonVirtualSize()
7403 .isZero())
7404 continue;
7405
7406 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7407 RecordLayout[FieldIndex] = Base;
7408 }
7409 // Fill in virtual bases.
7410 for (const auto &I : RD->vbases()) {
7411 const auto *Base = I.getType()->getAsCXXRecordDecl();
7412 // Ignore empty bases.
7413 if (Base->isEmpty())
7414 continue;
7415 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7416 if (RecordLayout[FieldIndex])
7417 continue;
7418 RecordLayout[FieldIndex] = Base;
7419 }
7420 // Fill in all the fields.
7421 assert(!RD->isUnion() && "Unexpected union.");
7422 for (const auto *Field : RD->fields()) {
7423 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7424 // will fill in later.)
7425 if (!Field->isBitField()) {
7426 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7427 RecordLayout[FieldIndex] = Field;
7428 }
7429 }
7430 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7431 &Data : RecordLayout) {
7432 if (Data.isNull())
7433 continue;
7434 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7435 getPlainLayout(Base, Layout, /*AsBase=*/true);
7436 else
7437 Layout.push_back(Data.get<const FieldDecl *>());
7438 }
7439 }
7440
Alexey Bataevb3638132018-07-19 16:34:13 +00007441public:
7442 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7443 : CurDir(Dir), CGF(CGF) {
7444 // Extract firstprivate clause information.
7445 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7446 for (const auto *D : C->varlists())
7447 FirstPrivateDecls.insert(
7448 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7449 // Extract device pointer clause information.
7450 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7451 for (auto L : C->component_lists())
7452 DevPointersMap[L.first].push_back(L.second);
7453 }
7454
7455 /// Generate code for the combined entry if we have a partially mapped struct
7456 /// and take care of the mapping flags of the arguments corresponding to
7457 /// individual struct members.
7458 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7459 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7460 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7461 const StructRangeInfoTy &PartialStruct) const {
7462 // Base is the base of the struct
7463 BasePointers.push_back(PartialStruct.Base.getPointer());
7464 // Pointer is the address of the lowest element
7465 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7466 Pointers.push_back(LB);
7467 // Size is (addr of {highest+1} element) - (addr of lowest element)
7468 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7469 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7470 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7471 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7472 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7473 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7474 /*isSinged=*/false);
7475 Sizes.push_back(Size);
7476 // Map type is always TARGET_PARAM
7477 Types.push_back(OMP_MAP_TARGET_PARAM);
7478 // Remove TARGET_PARAM flag from the first element
7479 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7480
7481 // All other current entries will be MEMBER_OF the combined entry
7482 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7483 // 0xFFFF in the MEMBER_OF field).
7484 OpenMPOffloadMappingFlags MemberOfFlag =
7485 getMemberOfFlag(BasePointers.size() - 1);
7486 for (auto &M : CurTypes)
7487 setCorrectMemberOfFlag(M, MemberOfFlag);
7488 }
7489
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007490 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007491 /// types for the extracted mappable expressions. Also, for each item that
7492 /// relates with a device pointer, a pair of the relevant declaration and
7493 /// index where it occurs is appended to the device pointers info array.
7494 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007495 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7496 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007497 // We have to process the component lists that relate with the same
7498 // declaration in a single chunk so that we can generate the map flags
7499 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007500 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007501
7502 // Helper function to fill the information map for the different supported
7503 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007504 auto &&InfoGen = [&Info](
7505 const ValueDecl *D,
7506 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
Kelvin Lief579432018-12-18 22:18:41 +00007507 OpenMPMapClauseKind MapType,
7508 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007509 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007510 const ValueDecl *VD =
7511 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Kelvin Lief579432018-12-18 22:18:41 +00007512 Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007513 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007514 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007515
Paul Robinson78fb1322016-08-01 22:12:46 +00007516 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007517 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7518 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007519 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifiers(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007520 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007521 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007522 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7523 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007524 InfoGen(L.first, L.second, OMPC_MAP_to, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007525 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007526 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007527 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7528 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007529 InfoGen(L.first, L.second, OMPC_MAP_from, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007530 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007531 }
Samuel Antao86ace552016-04-27 22:40:57 +00007532
Samuel Antaocc10b852016-07-28 14:23:26 +00007533 // Look at the use_device_ptr clause information and mark the existing map
7534 // entries as such. If there is no map information for an entry in the
7535 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007536 // section. It is the user fault if that was not mapped before. If there is
7537 // no map information and the pointer is a struct member, then we defer the
7538 // emission of that entry until the whole struct has been processed.
7539 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7540 DeferredInfo;
7541
Paul Robinson78fb1322016-08-01 22:12:46 +00007542 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007543 for (const auto *C :
7544 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007545 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007546 assert(!L.second.empty() && "Not expecting empty list of components!");
7547 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7548 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007549 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007550 // If the first component is a member expression, we have to look into
7551 // 'this', which maps to null in the map of map information. Otherwise
7552 // look directly for the information.
7553 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7554
7555 // We potentially have map information for this declaration already.
7556 // Look for the first set of components that refer to it.
7557 if (It != Info.end()) {
7558 auto CI = std::find_if(
7559 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7560 return MI.Components.back().getAssociatedDeclaration() == VD;
7561 });
7562 // If we found a map entry, signal that the pointer has to be returned
7563 // and move on to the next declaration.
7564 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007565 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007566 continue;
7567 }
7568 }
7569
7570 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007571 // size array section - if the pointer is a struct member we defer this
7572 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007573 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007574 if (isa<MemberExpr>(IE)) {
7575 // Insert the pointer into Info to be processed by
7576 // generateInfoForComponentList. Because it is a member pointer
7577 // without a pointee, no entry will be generated for it, therefore
7578 // we need to generate one after the whole struct has been processed.
7579 // Nonetheless, generateInfoForComponentList must be called to take
7580 // the pointer into account for the calculation of the range of the
7581 // partial struct.
Kelvin Lief579432018-12-18 22:18:41 +00007582 InfoGen(nullptr, L.second, OMPC_MAP_unknown, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007583 /*ReturnDevicePointer=*/false, C->isImplicit());
7584 DeferredInfo[nullptr].emplace_back(IE, VD);
7585 } else {
7586 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7587 this->CGF.EmitLValue(IE), IE->getExprLoc());
7588 BasePointers.emplace_back(Ptr, VD);
7589 Pointers.push_back(Ptr);
7590 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7591 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7592 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007593 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007594 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007595
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007596 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007597 // We need to know when we generate information for the first component
7598 // associated with a capture, because the mapping flags depend on it.
7599 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007600
7601 // Temporary versions of arrays
7602 MapBaseValuesArrayTy CurBasePointers;
7603 MapValuesArrayTy CurPointers;
7604 MapValuesArrayTy CurSizes;
7605 MapFlagsArrayTy CurTypes;
7606 StructRangeInfoTy PartialStruct;
7607
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007608 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007609 assert(!L.Components.empty() &&
7610 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007611
7612 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007613 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007614 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007615 this->generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007616 L.MapType, L.MapModifiers, L.Components, CurBasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007617 CurPointers, CurSizes, CurTypes, PartialStruct,
7618 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007619
7620 // If this entry relates with a device pointer, set the relevant
7621 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007622 if (L.ReturnDevicePointer) {
7623 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007624 "Unexpected number of mapped base pointers.");
7625
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007626 const ValueDecl *RelevantVD =
7627 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007628 assert(RelevantVD &&
7629 "No relevant declaration related with device pointer??");
7630
Alexey Bataevb3638132018-07-19 16:34:13 +00007631 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7632 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007633 }
Samuel Antao86ace552016-04-27 22:40:57 +00007634 IsFirstComponentList = false;
7635 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007636
7637 // Append any pending zero-length pointers which are struct members and
7638 // used with use_device_ptr.
7639 auto CI = DeferredInfo.find(M.first);
7640 if (CI != DeferredInfo.end()) {
7641 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7642 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7643 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7644 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7645 CurBasePointers.emplace_back(BasePtr, L.VD);
7646 CurPointers.push_back(Ptr);
7647 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7648 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7649 // value MEMBER_OF=FFFF so that the entry is later updated with the
7650 // correct value of MEMBER_OF.
7651 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7652 OMP_MAP_MEMBER_OF);
7653 }
7654 }
7655
7656 // If there is an entry in PartialStruct it means we have a struct with
7657 // individual members mapped. Emit an extra combined entry.
7658 if (PartialStruct.Base.isValid())
7659 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7660 PartialStruct);
7661
7662 // We need to append the results of this capture to what we already have.
7663 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7664 Pointers.append(CurPointers.begin(), CurPointers.end());
7665 Sizes.append(CurSizes.begin(), CurSizes.end());
7666 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007667 }
7668 }
7669
Alexey Bataev60705422018-10-30 15:50:12 +00007670 /// Emit capture info for lambdas for variables captured by reference.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007671 void generateInfoForLambdaCaptures(
7672 const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
7673 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7674 MapFlagsArrayTy &Types,
7675 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007676 const auto *RD = VD->getType()
7677 .getCanonicalType()
7678 .getNonReferenceType()
7679 ->getAsCXXRecordDecl();
7680 if (!RD || !RD->isLambda())
7681 return;
7682 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
7683 LValue VDLVal = CGF.MakeAddrLValue(
7684 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
7685 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
7686 FieldDecl *ThisCapture = nullptr;
7687 RD->getCaptureFields(Captures, ThisCapture);
7688 if (ThisCapture) {
7689 LValue ThisLVal =
7690 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007691 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
7692 LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
7693 BasePointers.push_back(ThisLVal.getPointer());
7694 Pointers.push_back(ThisLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007695 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007696 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007697 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7698 }
7699 for (const LambdaCapture &LC : RD->captures()) {
7700 if (LC.getCaptureKind() != LCK_ByRef)
7701 continue;
7702 const VarDecl *VD = LC.getCapturedVar();
7703 auto It = Captures.find(VD);
7704 assert(It != Captures.end() && "Found lambda capture without field.");
7705 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007706 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
7707 LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
7708 BasePointers.push_back(VarLVal.getPointer());
7709 Pointers.push_back(VarLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007710 Sizes.push_back(CGF.getTypeSize(
7711 VD->getType().getCanonicalType().getNonReferenceType()));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007712 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007713 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7714 }
7715 }
7716
7717 /// Set correct indices for lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007718 void adjustMemberOfForLambdaCaptures(
7719 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
7720 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
7721 MapFlagsArrayTy &Types) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007722 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
7723 // Set correct member_of idx for all implicit lambda captures.
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007724 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007725 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
7726 continue;
Alexey Bataev969dbc02018-11-08 15:47:39 +00007727 llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
7728 assert(BasePtr && "Unable to find base lambda address.");
Alexey Bataev60705422018-10-30 15:50:12 +00007729 int TgtIdx = -1;
7730 for (unsigned J = I; J > 0; --J) {
7731 unsigned Idx = J - 1;
7732 if (Pointers[Idx] != BasePtr)
7733 continue;
7734 TgtIdx = Idx;
7735 break;
7736 }
7737 assert(TgtIdx != -1 && "Unable to find parent lambda.");
7738 // All other current entries will be MEMBER_OF the combined entry
7739 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7740 // 0xFFFF in the MEMBER_OF field).
7741 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
7742 setCorrectMemberOfFlag(Types[I], MemberOfFlag);
7743 }
7744 }
7745
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007746 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007747 /// associated to a given capture.
7748 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007749 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007750 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007751 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007752 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7753 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007754 assert(!Cap->capturesVariableArrayType() &&
7755 "Not expecting to generate map info for a variable array type!");
7756
Samuel Antao6890b092016-07-28 14:25:09 +00007757 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007758 const ValueDecl *VD = Cap->capturesThis()
7759 ? nullptr
7760 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007761
Samuel Antao6890b092016-07-28 14:25:09 +00007762 // If this declaration appears in a is_device_ptr clause we just have to
7763 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007764 // pass its value.
7765 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007766 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007767 Pointers.push_back(Arg);
7768 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007769 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007770 return;
7771 }
7772
Alexey Bataeve82445f2018-09-20 13:54:02 +00007773 using MapData =
7774 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
Kelvin Lief579432018-12-18 22:18:41 +00007775 OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>, bool>;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007776 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007777 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007778 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007779 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007780 assert(L.first == VD &&
7781 "We got information for the wrong declaration??");
7782 assert(!L.second.empty() &&
7783 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007784 DeclComponentLists.emplace_back(L.second, C->getMapType(),
Kelvin Lief579432018-12-18 22:18:41 +00007785 C->getMapTypeModifiers(),
Alexey Bataeve82445f2018-09-20 13:54:02 +00007786 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007787 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007788 }
7789
7790 // Find overlapping elements (including the offset from the base element).
7791 llvm::SmallDenseMap<
7792 const MapData *,
7793 llvm::SmallVector<
7794 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7795 4>
7796 OverlappedData;
7797 size_t Count = 0;
7798 for (const MapData &L : DeclComponentLists) {
7799 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7800 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007801 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007802 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007803 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007804 ++Count;
7805 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7806 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
Kelvin Lief579432018-12-18 22:18:41 +00007807 std::tie(Components1, MapType, MapModifiers, IsImplicit) = L1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007808 auto CI = Components.rbegin();
7809 auto CE = Components.rend();
7810 auto SI = Components1.rbegin();
7811 auto SE = Components1.rend();
7812 for (; CI != CE && SI != SE; ++CI, ++SI) {
7813 if (CI->getAssociatedExpression()->getStmtClass() !=
7814 SI->getAssociatedExpression()->getStmtClass())
7815 break;
7816 // Are we dealing with different variables/fields?
7817 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7818 break;
7819 }
7820 // Found overlapping if, at least for one component, reached the head of
7821 // the components list.
7822 if (CI == CE || SI == SE) {
7823 assert((CI != CE || SI != SE) &&
7824 "Unexpected full match of the mapping components.");
7825 const MapData &BaseData = CI == CE ? L : L1;
7826 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7827 SI == SE ? Components : Components1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007828 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7829 OverlappedElements.getSecond().push_back(SubData);
7830 }
7831 }
7832 }
7833 // Sort the overlapped elements for each item.
7834 llvm::SmallVector<const FieldDecl *, 4> Layout;
7835 if (!OverlappedData.empty()) {
7836 if (const auto *CRD =
7837 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7838 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7839 else {
7840 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7841 Layout.append(RD->field_begin(), RD->field_end());
7842 }
7843 }
7844 for (auto &Pair : OverlappedData) {
7845 llvm::sort(
7846 Pair.getSecond(),
7847 [&Layout](
7848 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7849 OMPClauseMappableExprCommon::MappableExprComponentListRef
7850 Second) {
7851 auto CI = First.rbegin();
7852 auto CE = First.rend();
7853 auto SI = Second.rbegin();
7854 auto SE = Second.rend();
7855 for (; CI != CE && SI != SE; ++CI, ++SI) {
7856 if (CI->getAssociatedExpression()->getStmtClass() !=
7857 SI->getAssociatedExpression()->getStmtClass())
7858 break;
7859 // Are we dealing with different variables/fields?
7860 if (CI->getAssociatedDeclaration() !=
7861 SI->getAssociatedDeclaration())
7862 break;
7863 }
Richard Trieu5061e832018-09-21 21:20:33 +00007864
7865 // Lists contain the same elements.
7866 if (CI == CE && SI == SE)
7867 return false;
7868
7869 // List with less elements is less than list with more elements.
7870 if (CI == CE || SI == SE)
7871 return CI == CE;
7872
Alexey Bataeve82445f2018-09-20 13:54:02 +00007873 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7874 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7875 if (FD1->getParent() == FD2->getParent())
7876 return FD1->getFieldIndex() < FD2->getFieldIndex();
7877 const auto It =
7878 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7879 return FD == FD1 || FD == FD2;
7880 });
7881 return *It == FD1;
7882 });
7883 }
7884
7885 // Associated with a capture, because the mapping flags depend on it.
7886 // Go through all of the elements with the overlapped elements.
7887 for (const auto &Pair : OverlappedData) {
7888 const MapData &L = *Pair.getFirst();
7889 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7890 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007891 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007892 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007893 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007894 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7895 OverlappedComponents = Pair.getSecond();
7896 bool IsFirstComponentList = true;
Kelvin Lief579432018-12-18 22:18:41 +00007897 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007898 BasePointers, Pointers, Sizes, Types,
7899 PartialStruct, IsFirstComponentList,
7900 IsImplicit, OverlappedComponents);
7901 }
7902 // Go through other elements without overlapped elements.
7903 bool IsFirstComponentList = OverlappedData.empty();
7904 for (const MapData &L : DeclComponentLists) {
7905 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7906 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007907 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007908 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007909 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007910 auto It = OverlappedData.find(&L);
7911 if (It == OverlappedData.end())
Kelvin Lief579432018-12-18 22:18:41 +00007912 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007913 BasePointers, Pointers, Sizes, Types,
7914 PartialStruct, IsFirstComponentList,
7915 IsImplicit);
7916 IsFirstComponentList = false;
7917 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007918 }
Samuel Antao86ace552016-04-27 22:40:57 +00007919
Alexey Bataevb3638132018-07-19 16:34:13 +00007920 /// Generate the base pointers, section pointers, sizes and map types
7921 /// associated with the declare target link variables.
7922 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7923 MapValuesArrayTy &Pointers,
7924 MapValuesArrayTy &Sizes,
7925 MapFlagsArrayTy &Types) const {
7926 // Map other list items in the map clause which are not captured variables
7927 // but "declare target link" global variables.,
7928 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7929 for (const auto &L : C->component_lists()) {
7930 if (!L.first)
7931 continue;
7932 const auto *VD = dyn_cast<VarDecl>(L.first);
7933 if (!VD)
7934 continue;
7935 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007936 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007937 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7938 continue;
7939 StructRangeInfoTy PartialStruct;
7940 generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007941 C->getMapType(), C->getMapTypeModifiers(), L.second, BasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007942 Pointers, Sizes, Types, PartialStruct,
7943 /*IsFirstComponentList=*/true, C->isImplicit());
7944 assert(!PartialStruct.Base.isValid() &&
7945 "No partial structs for declare target link expected.");
7946 }
7947 }
Samuel Antao86ace552016-04-27 22:40:57 +00007948 }
Samuel Antaod486f842016-05-26 16:53:38 +00007949
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007950 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007951 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007952 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7953 const FieldDecl &RI, llvm::Value *CV,
7954 MapBaseValuesArrayTy &CurBasePointers,
7955 MapValuesArrayTy &CurPointers,
7956 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007957 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007958 // Do the default mapping.
7959 if (CI.capturesThis()) {
7960 CurBasePointers.push_back(CV);
7961 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007962 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007963 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7964 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007965 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007966 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007967 CurBasePointers.push_back(CV);
7968 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007969 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007970 // We have to signal to the runtime captures passed by value that are
7971 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007972 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007973 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7974 } else {
7975 // Pointers are implicitly mapped with a zero size and no flags
7976 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007977 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007978 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7979 }
7980 } else {
7981 assert(CI.capturesVariable() && "Expected captured reference.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007982 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007983 QualType ElementType = PtrTy->getPointeeType();
7984 CurSizes.push_back(CGF.getTypeSize(ElementType));
7985 // The default map type for a scalar/complex type is 'to' because by
7986 // default the value doesn't have to be retrieved. For an aggregate
7987 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007988 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Alexey Bataev1af5bd52019-03-05 17:47:18 +00007989 const VarDecl *VD = CI.getCapturedVar();
7990 if (FirstPrivateDecls.count(VD) &&
7991 VD->getType().isConstant(CGF.getContext())) {
7992 llvm::Constant *Addr =
7993 CGF.CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(CGF, VD);
7994 // Copy the value of the original variable to the new global copy.
7995 CGF.Builder.CreateMemCpy(
7996 CGF.MakeNaturalAlignAddrLValue(Addr, ElementType).getAddress(),
7997 Address(CV, CGF.getContext().getTypeAlignInChars(ElementType)),
Alexey Bataevc2b831f2019-04-02 16:03:40 +00007998 CurSizes.back(), /*isVolatile=*/false);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00007999 // Use new global variable as the base pointers.
8000 CurBasePointers.push_back(Addr);
8001 CurPointers.push_back(Addr);
8002 } else {
8003 CurBasePointers.push_back(CV);
Alexey Bataevc2b831f2019-04-02 16:03:40 +00008004 if (FirstPrivateDecls.count(VD) && ElementType->isAnyPointerType()) {
8005 Address PtrAddr = CGF.EmitLoadOfReference(CGF.MakeAddrLValue(
8006 CV, ElementType, CGF.getContext().getDeclAlign(VD),
8007 AlignmentSource::Decl));
8008 CurPointers.push_back(PtrAddr.getPointer());
8009 } else {
8010 CurPointers.push_back(CV);
8011 }
Alexey Bataev1af5bd52019-03-05 17:47:18 +00008012 }
Samuel Antaod486f842016-05-26 16:53:38 +00008013 }
George Rokos065755d2017-11-07 18:27:04 +00008014 // Every default map produces a single argument which is a target parameter.
8015 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00008016
8017 // Add flag stating this is an implicit map.
8018 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00008019 }
Samuel Antao86ace552016-04-27 22:40:57 +00008020};
Samuel Antaodf158d52016-04-27 22:58:19 +00008021
8022enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008023 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00008024 /// from environment variables in the spec.
8025 OMP_DEVICEID_UNDEF = -1,
8026};
8027} // anonymous namespace
8028
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008029/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00008030/// offloading runtime library. If there is no map or capture information,
8031/// return nullptr by reference.
8032static void
Samuel Antaocc10b852016-07-28 14:23:26 +00008033emitOffloadingArrays(CodeGenFunction &CGF,
8034 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00008035 MappableExprsHandler::MapValuesArrayTy &Pointers,
8036 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00008037 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
8038 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008039 CodeGenModule &CGM = CGF.CGM;
8040 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00008041
Samuel Antaocc10b852016-07-28 14:23:26 +00008042 // Reset the array information.
8043 Info.clearArrayInfo();
8044 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00008045
Samuel Antaocc10b852016-07-28 14:23:26 +00008046 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008047 // Detect if we have any capture size requiring runtime evaluation of the
8048 // size so that a constant array could be eventually used.
8049 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008050 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00008051 if (!isa<llvm::Constant>(S)) {
8052 hasRuntimeEvaluationCaptureSize = true;
8053 break;
8054 }
8055
Samuel Antaocc10b852016-07-28 14:23:26 +00008056 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00008057 QualType PointerArrayType =
8058 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
8059 /*IndexTypeQuals=*/0);
8060
Samuel Antaocc10b852016-07-28 14:23:26 +00008061 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00008062 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00008063 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00008064 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
8065
8066 // If we don't have any VLA types or other types that require runtime
8067 // evaluation, we can use a constant array for the map sizes, otherwise we
8068 // need to fill up the arrays as we do for the pointers.
8069 if (hasRuntimeEvaluationCaptureSize) {
8070 QualType SizeArrayType = Ctx.getConstantArrayType(
8071 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
8072 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00008073 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00008074 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
8075 } else {
8076 // We expect all the sizes to be constant, so we collect them to create
8077 // a constant array.
8078 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008079 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00008080 ConstSizes.push_back(cast<llvm::Constant>(S));
8081
8082 auto *SizesArrayInit = llvm::ConstantArray::get(
8083 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008084 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008085 auto *SizesArrayGbl = new llvm::GlobalVariable(
8086 CGM.getModule(), SizesArrayInit->getType(),
8087 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008088 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008089 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008090 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008091 }
8092
8093 // The map types are always constant so we don't need to generate code to
8094 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00008095 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
8096 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00008097 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00008098 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008099 std::string MaptypesName =
8100 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008101 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
8102 CGM.getModule(), MapTypesArrayInit->getType(),
8103 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008104 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008105 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008106 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008107
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008108 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
8109 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008110 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008111 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008112 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008113 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8114 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008115 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8116 CGF.Builder.CreateStore(BPVal, BPAddr);
8117
Samuel Antaocc10b852016-07-28 14:23:26 +00008118 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008119 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00008120 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00008121
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008122 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008123 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008124 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008125 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008126 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8127 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008128 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8129 CGF.Builder.CreateStore(PVal, PAddr);
8130
8131 if (hasRuntimeEvaluationCaptureSize) {
8132 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008133 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
8134 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008135 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008136 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00008137 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
8138 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008139 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00008140 SAddr);
8141 }
8142 }
8143 }
8144}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008145/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00008146/// arrays of pointers, sizes and map types.
8147static void emitOffloadingArraysArgument(
8148 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
8149 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008150 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008151 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00008152 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008153 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008154 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8155 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008156 /*Idx0=*/0, /*Idx1=*/0);
8157 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008158 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8159 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008160 /*Idx0=*/0,
8161 /*Idx1=*/0);
8162 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008163 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008164 /*Idx0=*/0, /*Idx1=*/0);
8165 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00008166 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00008167 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008168 /*Idx0=*/0,
8169 /*Idx1=*/0);
8170 } else {
8171 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8172 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8173 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
8174 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00008175 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00008176 }
Samuel Antao86ace552016-04-27 22:40:57 +00008177}
8178
Alexey Bataev7bb33532019-01-07 21:30:43 +00008179/// Checks if the expression is constant or does not have non-trivial function
8180/// calls.
8181static bool isTrivial(ASTContext &Ctx, const Expr * E) {
8182 // We can skip constant expressions.
8183 // We can skip expressions with trivial calls or simple expressions.
8184 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
8185 !E->hasNonTrivialCall(Ctx)) &&
8186 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
8187}
8188
8189/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
8190/// iff there is only one that is not evaluatable at the compile time.
8191static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
8192 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
8193 const Stmt *Child = nullptr;
8194 for (const Stmt *S : C->body()) {
8195 if (const auto *E = dyn_cast<Expr>(S)) {
8196 if (isTrivial(Ctx, E))
8197 continue;
8198 }
8199 // Some of the statements can be ignored.
8200 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
8201 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
8202 continue;
8203 // Analyze declarations.
8204 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
8205 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
8206 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
8207 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
8208 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
8209 isa<UsingDirectiveDecl>(D) ||
8210 isa<OMPDeclareReductionDecl>(D) ||
8211 isa<OMPThreadPrivateDecl>(D))
8212 return true;
8213 const auto *VD = dyn_cast<VarDecl>(D);
8214 if (!VD)
8215 return false;
8216 return VD->isConstexpr() ||
8217 ((VD->getType().isTrivialType(Ctx) ||
8218 VD->getType()->isReferenceType()) &&
8219 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
8220 }))
8221 continue;
8222 }
8223 // Found multiple children - cannot get the one child only.
8224 if (Child)
8225 return Body;
8226 Child = S;
8227 }
8228 if (Child)
8229 return Child;
8230 }
8231 return Body;
8232}
8233
8234/// Check for inner distribute directive.
8235static const OMPExecutableDirective *
8236getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) {
8237 const auto *CS = D.getInnermostCapturedStmt();
8238 const auto *Body =
8239 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
8240 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
8241
8242 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8243 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
8244 switch (D.getDirectiveKind()) {
8245 case OMPD_target:
8246 if (isOpenMPDistributeDirective(DKind))
8247 return NestedDir;
8248 if (DKind == OMPD_teams) {
8249 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
8250 /*IgnoreCaptured=*/true);
8251 if (!Body)
8252 return nullptr;
8253 ChildStmt = getSingleCompoundChild(Ctx, Body);
8254 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8255 DKind = NND->getDirectiveKind();
8256 if (isOpenMPDistributeDirective(DKind))
8257 return NND;
8258 }
8259 }
8260 return nullptr;
8261 case OMPD_target_teams:
8262 if (isOpenMPDistributeDirective(DKind))
8263 return NestedDir;
8264 return nullptr;
8265 case OMPD_target_parallel:
8266 case OMPD_target_simd:
8267 case OMPD_target_parallel_for:
8268 case OMPD_target_parallel_for_simd:
8269 return nullptr;
8270 case OMPD_target_teams_distribute:
8271 case OMPD_target_teams_distribute_simd:
8272 case OMPD_target_teams_distribute_parallel_for:
8273 case OMPD_target_teams_distribute_parallel_for_simd:
8274 case OMPD_parallel:
8275 case OMPD_for:
8276 case OMPD_parallel_for:
8277 case OMPD_parallel_sections:
8278 case OMPD_for_simd:
8279 case OMPD_parallel_for_simd:
8280 case OMPD_cancel:
8281 case OMPD_cancellation_point:
8282 case OMPD_ordered:
8283 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008284 case OMPD_allocate:
Alexey Bataev7bb33532019-01-07 21:30:43 +00008285 case OMPD_task:
8286 case OMPD_simd:
8287 case OMPD_sections:
8288 case OMPD_section:
8289 case OMPD_single:
8290 case OMPD_master:
8291 case OMPD_critical:
8292 case OMPD_taskyield:
8293 case OMPD_barrier:
8294 case OMPD_taskwait:
8295 case OMPD_taskgroup:
8296 case OMPD_atomic:
8297 case OMPD_flush:
8298 case OMPD_teams:
8299 case OMPD_target_data:
8300 case OMPD_target_exit_data:
8301 case OMPD_target_enter_data:
8302 case OMPD_distribute:
8303 case OMPD_distribute_simd:
8304 case OMPD_distribute_parallel_for:
8305 case OMPD_distribute_parallel_for_simd:
8306 case OMPD_teams_distribute:
8307 case OMPD_teams_distribute_simd:
8308 case OMPD_teams_distribute_parallel_for:
8309 case OMPD_teams_distribute_parallel_for_simd:
8310 case OMPD_target_update:
8311 case OMPD_declare_simd:
8312 case OMPD_declare_target:
8313 case OMPD_end_declare_target:
8314 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008315 case OMPD_declare_mapper:
Alexey Bataev7bb33532019-01-07 21:30:43 +00008316 case OMPD_taskloop:
8317 case OMPD_taskloop_simd:
8318 case OMPD_requires:
8319 case OMPD_unknown:
8320 llvm_unreachable("Unexpected directive.");
8321 }
8322 }
8323
8324 return nullptr;
8325}
8326
8327void CGOpenMPRuntime::emitTargetNumIterationsCall(
8328 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *Device,
8329 const llvm::function_ref<llvm::Value *(
8330 CodeGenFunction &CGF, const OMPLoopDirective &D)> &SizeEmitter) {
8331 OpenMPDirectiveKind Kind = D.getDirectiveKind();
8332 const OMPExecutableDirective *TD = &D;
8333 // Get nested teams distribute kind directive, if any.
8334 if (!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind))
8335 TD = getNestedDistributeDirective(CGM.getContext(), D);
8336 if (!TD)
8337 return;
8338 const auto *LD = cast<OMPLoopDirective>(TD);
8339 auto &&CodeGen = [LD, &Device, &SizeEmitter, this](CodeGenFunction &CGF,
8340 PrePostActionTy &) {
8341 llvm::Value *NumIterations = SizeEmitter(CGF, *LD);
8342
8343 // Emit device ID if any.
8344 llvm::Value *DeviceID;
8345 if (Device)
8346 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
8347 CGF.Int64Ty, /*isSigned=*/true);
8348 else
8349 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8350
8351 llvm::Value *Args[] = {DeviceID, NumIterations};
8352 CGF.EmitRuntimeCall(
8353 createRuntimeFunction(OMPRTL__kmpc_push_target_tripcount), Args);
8354 };
8355 emitInlinedDirective(CGF, OMPD_unknown, CodeGen);
8356}
8357
Samuel Antaobed3c462015-10-02 16:14:20 +00008358void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
8359 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00008360 llvm::Function *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00008361 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008362 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00008363 if (!CGF.HaveInsertPoint())
8364 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00008365
Samuel Antaoee8fb302016-01-06 13:42:12 +00008366 assert(OutlinedFn && "Invalid outlined function!");
8367
Alexey Bataev8451efa2018-01-15 19:06:12 +00008368 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
8369 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00008370 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008371 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
8372 PrePostActionTy &) {
8373 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8374 };
8375 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00008376
Alexey Bataev8451efa2018-01-15 19:06:12 +00008377 CodeGenFunction::OMPTargetDataInfo InputInfo;
8378 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00008379 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008380 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
8381 &MapTypesArray, &CS, RequiresOuterTask,
8382 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008383 // On top of the arrays that were filled up, the target offloading call
8384 // takes as arguments the device id as well as the host pointer. The host
8385 // pointer is used by the runtime library to identify the current target
8386 // region, so it only has to be unique and not necessarily point to
8387 // anything. It could be the pointer to the outlined function that
8388 // implements the target region, but we aren't using that so that the
8389 // compiler doesn't need to keep that, and could therefore inline the host
8390 // function if proven worthwhile during optimization.
8391
Samuel Antaoee8fb302016-01-06 13:42:12 +00008392 // From this point on, we need to have an ID of the target region defined.
8393 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00008394
8395 // Emit device ID if any.
8396 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00008397 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008398 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008399 CGF.Int64Ty, /*isSigned=*/true);
8400 } else {
8401 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8402 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008403
Samuel Antaodf158d52016-04-27 22:58:19 +00008404 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008405 llvm::Value *PointerNum =
8406 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00008407
Samuel Antaob68e2db2016-03-03 16:20:23 +00008408 // Return value of the runtime offloading call.
8409 llvm::Value *Return;
8410
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008411 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
8412 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008413
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008414 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008415 // The target region is an outlined function launched by the runtime
8416 // via calls __tgt_target() or __tgt_target_teams().
8417 //
8418 // __tgt_target() launches a target region with one team and one thread,
8419 // executing a serial region. This master thread may in turn launch
8420 // more threads within its team upon encountering a parallel region,
8421 // however, no additional teams can be launched on the device.
8422 //
8423 // __tgt_target_teams() launches a target region with one or more teams,
8424 // each with one or more threads. This call is required for target
8425 // constructs such as:
8426 // 'target teams'
8427 // 'target' / 'teams'
8428 // 'target teams distribute parallel for'
8429 // 'target parallel'
8430 // and so on.
8431 //
8432 // Note that on the host and CPU targets, the runtime implementation of
8433 // these calls simply call the outlined function without forking threads.
8434 // The outlined functions themselves have runtime calls to
8435 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
8436 // the compiler in emitTeamsCall() and emitParallelCall().
8437 //
8438 // In contrast, on the NVPTX target, the implementation of
8439 // __tgt_target_teams() launches a GPU kernel with the requested number
8440 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00008441 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008442 // If we have NumTeams defined this means that we have an enclosed teams
8443 // region. Therefore we also expect to have NumThreads defined. These two
8444 // values should be defined in the presence of a teams directive,
8445 // regardless of having any clauses associated. If the user is using teams
8446 // but no clauses, these two values will be the default that should be
8447 // passed to the runtime library - a 32-bit integer with the value zero.
8448 assert(NumThreads && "Thread limit expression should be available along "
8449 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00008450 llvm::Value *OffloadingArgs[] = {DeviceID,
8451 OutlinedFnID,
8452 PointerNum,
8453 InputInfo.BasePointersArray.getPointer(),
8454 InputInfo.PointersArray.getPointer(),
8455 InputInfo.SizesArray.getPointer(),
8456 MapTypesArray,
8457 NumTeams,
8458 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00008459 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008460 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8461 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008462 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008463 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008464 llvm::Value *OffloadingArgs[] = {DeviceID,
8465 OutlinedFnID,
8466 PointerNum,
8467 InputInfo.BasePointersArray.getPointer(),
8468 InputInfo.PointersArray.getPointer(),
8469 InputInfo.SizesArray.getPointer(),
8470 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008471 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008472 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8473 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008474 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008475 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008476
Alexey Bataev2a007e02017-10-02 14:20:58 +00008477 // Check the error code and execute the host version if required.
8478 llvm::BasicBlock *OffloadFailedBlock =
8479 CGF.createBasicBlock("omp_offload.failed");
8480 llvm::BasicBlock *OffloadContBlock =
8481 CGF.createBasicBlock("omp_offload.cont");
8482 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8483 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8484
8485 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008486 if (RequiresOuterTask) {
8487 CapturedVars.clear();
8488 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8489 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008490 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008491 CGF.EmitBranch(OffloadContBlock);
8492
8493 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008494 };
8495
Samuel Antaoee8fb302016-01-06 13:42:12 +00008496 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008497 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8498 RequiresOuterTask](CodeGenFunction &CGF,
8499 PrePostActionTy &) {
8500 if (RequiresOuterTask) {
8501 CapturedVars.clear();
8502 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8503 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008504 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008505 };
8506
8507 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8508 &CapturedVars, RequiresOuterTask,
8509 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8510 // Fill up the arrays with all the captured variables.
8511 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8512 MappableExprsHandler::MapValuesArrayTy Pointers;
8513 MappableExprsHandler::MapValuesArrayTy Sizes;
8514 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8515
Alexey Bataev8451efa2018-01-15 19:06:12 +00008516 // Get mappable expression information.
8517 MappableExprsHandler MEHandler(D, CGF);
Alexey Bataev969dbc02018-11-08 15:47:39 +00008518 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008519
8520 auto RI = CS.getCapturedRecordDecl()->field_begin();
8521 auto CV = CapturedVars.begin();
8522 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8523 CE = CS.capture_end();
8524 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008525 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8526 MappableExprsHandler::MapValuesArrayTy CurPointers;
8527 MappableExprsHandler::MapValuesArrayTy CurSizes;
8528 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8529 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008530
8531 // VLA sizes are passed to the outlined region by copy and do not have map
8532 // information associated.
8533 if (CI->capturesVariableArrayType()) {
8534 CurBasePointers.push_back(*CV);
8535 CurPointers.push_back(*CV);
8536 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8537 // Copy to the device as an argument. No need to retrieve it.
8538 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8539 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8540 } else {
8541 // If we have any information in the map clause, we use it, otherwise we
8542 // just do a default mapping.
8543 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008544 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008545 if (CurBasePointers.empty())
8546 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8547 CurPointers, CurSizes, CurMapTypes);
Alexey Bataev60705422018-10-30 15:50:12 +00008548 // Generate correct mapping for variables captured by reference in
8549 // lambdas.
8550 if (CI->capturesVariable())
Alexey Bataev969dbc02018-11-08 15:47:39 +00008551 MEHandler.generateInfoForLambdaCaptures(
8552 CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
8553 CurMapTypes, LambdaPointers);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008554 }
8555 // We expect to have at least an element of information for this capture.
8556 assert(!CurBasePointers.empty() &&
8557 "Non-existing map pointer for capture!");
8558 assert(CurBasePointers.size() == CurPointers.size() &&
8559 CurBasePointers.size() == CurSizes.size() &&
8560 CurBasePointers.size() == CurMapTypes.size() &&
8561 "Inconsistent map information sizes!");
8562
Alexey Bataevb3638132018-07-19 16:34:13 +00008563 // If there is an entry in PartialStruct it means we have a struct with
8564 // individual members mapped. Emit an extra combined entry.
8565 if (PartialStruct.Base.isValid())
8566 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8567 CurMapTypes, PartialStruct);
8568
Alexey Bataev8451efa2018-01-15 19:06:12 +00008569 // We need to append the results of this capture to what we already have.
8570 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8571 Pointers.append(CurPointers.begin(), CurPointers.end());
8572 Sizes.append(CurSizes.begin(), CurSizes.end());
8573 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8574 }
Alexey Bataev60705422018-10-30 15:50:12 +00008575 // Adjust MEMBER_OF flags for the lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00008576 MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
8577 Pointers, MapTypes);
Alexey Bataev92327c52018-03-26 16:40:55 +00008578 // Map other list items in the map clause which are not captured variables
8579 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008580 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8581 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008582
8583 TargetDataInfo Info;
8584 // Fill up the arrays and create the arguments.
8585 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8586 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8587 Info.PointersArray, Info.SizesArray,
8588 Info.MapTypesArray, Info);
8589 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8590 InputInfo.BasePointersArray =
8591 Address(Info.BasePointersArray, CGM.getPointerAlign());
8592 InputInfo.PointersArray =
8593 Address(Info.PointersArray, CGM.getPointerAlign());
8594 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8595 MapTypesArray = Info.MapTypesArray;
8596 if (RequiresOuterTask)
8597 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8598 else
8599 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8600 };
8601
8602 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8603 CodeGenFunction &CGF, PrePostActionTy &) {
8604 if (RequiresOuterTask) {
8605 CodeGenFunction::OMPTargetDataInfo InputInfo;
8606 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8607 } else {
8608 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8609 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008610 };
8611
8612 // If we have a target function ID it means that we need to support
8613 // offloading, otherwise, just execute on the host. We need to execute on host
8614 // regardless of the conditional in the if clause if, e.g., the user do not
8615 // specify target triples.
8616 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008617 if (IfCond) {
8618 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8619 } else {
8620 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008621 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008622 }
8623 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008624 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008625 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008626 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008627}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008628
8629void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8630 StringRef ParentName) {
8631 if (!S)
8632 return;
8633
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008634 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008635 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008636 isa<OMPExecutableDirective>(S) &&
8637 isOpenMPTargetExecutionDirective(
8638 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008639
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008640 if (RequiresDeviceCodegen) {
8641 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008642 unsigned DeviceID;
8643 unsigned FileID;
8644 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008645 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008646 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008647
8648 // Is this a target region that should not be emitted as an entry point? If
8649 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008650 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8651 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008652 return;
8653
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008654 switch (E.getDirectiveKind()) {
8655 case OMPD_target:
8656 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8657 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008658 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008659 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008660 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008661 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008662 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008663 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008664 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008665 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008666 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008667 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008668 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008669 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008670 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008671 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008672 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008673 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008674 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008675 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008676 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008677 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008678 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008679 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008680 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008681 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008682 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008683 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008684 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008685 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008686 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008687 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008688 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8689 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008690 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008691 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008692 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008693 CodeGenFunction::
8694 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8695 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008696 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008697 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008698 case OMPD_parallel:
8699 case OMPD_for:
8700 case OMPD_parallel_for:
8701 case OMPD_parallel_sections:
8702 case OMPD_for_simd:
8703 case OMPD_parallel_for_simd:
8704 case OMPD_cancel:
8705 case OMPD_cancellation_point:
8706 case OMPD_ordered:
8707 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008708 case OMPD_allocate:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008709 case OMPD_task:
8710 case OMPD_simd:
8711 case OMPD_sections:
8712 case OMPD_section:
8713 case OMPD_single:
8714 case OMPD_master:
8715 case OMPD_critical:
8716 case OMPD_taskyield:
8717 case OMPD_barrier:
8718 case OMPD_taskwait:
8719 case OMPD_taskgroup:
8720 case OMPD_atomic:
8721 case OMPD_flush:
8722 case OMPD_teams:
8723 case OMPD_target_data:
8724 case OMPD_target_exit_data:
8725 case OMPD_target_enter_data:
8726 case OMPD_distribute:
8727 case OMPD_distribute_simd:
8728 case OMPD_distribute_parallel_for:
8729 case OMPD_distribute_parallel_for_simd:
8730 case OMPD_teams_distribute:
8731 case OMPD_teams_distribute_simd:
8732 case OMPD_teams_distribute_parallel_for:
8733 case OMPD_teams_distribute_parallel_for_simd:
8734 case OMPD_target_update:
8735 case OMPD_declare_simd:
8736 case OMPD_declare_target:
8737 case OMPD_end_declare_target:
8738 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008739 case OMPD_declare_mapper:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008740 case OMPD_taskloop:
8741 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008742 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008743 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008744 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8745 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008746 return;
8747 }
8748
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008749 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008750 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008751 return;
8752
8753 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008754 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008755 return;
8756 }
8757
8758 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008759 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008760 S = L->getBody();
8761
8762 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008763 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008764 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008765}
8766
8767bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008768 // If emitting code for the host, we do not process FD here. Instead we do
8769 // the normal code generation.
8770 if (!CGM.getLangOpts().OpenMPIsDevice)
8771 return false;
8772
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008773 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008774 StringRef Name = CGM.getMangledName(GD);
8775 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008776 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008777 scanForTargetRegionsFunctions(FD->getBody(), Name);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008778
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008779 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008780 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008781 AlreadyEmittedTargetFunctions.count(Name) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008782}
8783
8784bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8785 if (!CGM.getLangOpts().OpenMPIsDevice)
8786 return false;
8787
8788 // Check if there are Ctors/Dtors in this declaration and look for target
8789 // regions in it. We use the complete variant to produce the kernel name
8790 // mangling.
8791 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008792 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8793 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008794 StringRef ParentName =
8795 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8796 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8797 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008798 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008799 StringRef ParentName =
8800 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8801 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8802 }
8803 }
8804
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008805 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008806 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008807 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8808 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008809 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008810 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008811 return true;
8812 }
8813 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008814}
8815
Alexey Bataev1af5bd52019-03-05 17:47:18 +00008816llvm::Constant *
8817CGOpenMPRuntime::registerTargetFirstprivateCopy(CodeGenFunction &CGF,
8818 const VarDecl *VD) {
8819 assert(VD->getType().isConstant(CGM.getContext()) &&
8820 "Expected constant variable.");
8821 StringRef VarName;
8822 llvm::Constant *Addr;
8823 llvm::GlobalValue::LinkageTypes Linkage;
8824 QualType Ty = VD->getType();
8825 SmallString<128> Buffer;
8826 {
8827 unsigned DeviceID;
8828 unsigned FileID;
8829 unsigned Line;
8830 getTargetEntryUniqueInfo(CGM.getContext(), VD->getLocation(), DeviceID,
8831 FileID, Line);
8832 llvm::raw_svector_ostream OS(Buffer);
8833 OS << "__omp_offloading_firstprivate_" << llvm::format("_%x", DeviceID)
8834 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
8835 VarName = OS.str();
8836 }
8837 Linkage = llvm::GlobalValue::InternalLinkage;
8838 Addr =
8839 getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(Ty), VarName,
8840 getDefaultFirstprivateAddressSpace());
8841 cast<llvm::GlobalValue>(Addr)->setLinkage(Linkage);
8842 CharUnits VarSize = CGM.getContext().getTypeSizeInChars(Ty);
8843 CGM.addCompilerUsedGlobal(cast<llvm::GlobalValue>(Addr));
8844 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8845 VarName, Addr, VarSize,
8846 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo, Linkage);
8847 return Addr;
8848}
8849
Alexey Bataev03f270c2018-03-30 18:31:07 +00008850void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8851 llvm::Constant *Addr) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008852 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
8853 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
8854 if (!Res) {
8855 if (CGM.getLangOpts().OpenMPIsDevice) {
8856 // Register non-target variables being emitted in device code (debug info
8857 // may cause this).
8858 StringRef VarName = CGM.getMangledName(VD);
8859 EmittedNonTargetVariables.try_emplace(VarName, Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008860 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008861 return;
Alexey Bataev03f270c2018-03-30 18:31:07 +00008862 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008863 // Register declare target variables.
8864 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8865 StringRef VarName;
8866 CharUnits VarSize;
8867 llvm::GlobalValue::LinkageTypes Linkage;
8868 switch (*Res) {
8869 case OMPDeclareTargetDeclAttr::MT_To:
8870 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8871 VarName = CGM.getMangledName(VD);
8872 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8873 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8874 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8875 } else {
8876 VarSize = CharUnits::Zero();
8877 }
8878 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
8879 // Temp solution to prevent optimizations of the internal variables.
8880 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8881 std::string RefName = getName({VarName, "ref"});
8882 if (!CGM.GetGlobalValue(RefName)) {
8883 llvm::Constant *AddrRef =
8884 getOrCreateInternalVariable(Addr->getType(), RefName);
8885 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8886 GVAddrRef->setConstant(/*Val=*/true);
8887 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8888 GVAddrRef->setInitializer(Addr);
8889 CGM.addCompilerUsedGlobal(GVAddrRef);
8890 }
8891 }
8892 break;
8893 case OMPDeclareTargetDeclAttr::MT_Link:
8894 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8895 if (CGM.getLangOpts().OpenMPIsDevice) {
8896 VarName = Addr->getName();
8897 Addr = nullptr;
8898 } else {
8899 VarName = getAddrOfDeclareTargetLink(VD).getName();
8900 Addr = cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8901 }
8902 VarSize = CGM.getPointerSize();
8903 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8904 break;
8905 }
8906 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8907 VarName, Addr, VarSize, Flags, Linkage);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008908}
8909
Samuel Antaoee8fb302016-01-06 13:42:12 +00008910bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008911 if (isa<FunctionDecl>(GD.getDecl()) ||
8912 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008913 return emitTargetFunctions(GD);
8914
8915 return emitTargetGlobalVariable(GD);
8916}
8917
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008918void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8919 for (const VarDecl *VD : DeferredGlobalVariables) {
8920 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008921 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008922 if (!Res)
8923 continue;
8924 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008925 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008926 } else {
8927 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8928 "Expected to or link clauses.");
8929 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008930 }
8931 }
8932}
8933
Alexey Bataev60705422018-10-30 15:50:12 +00008934void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
8935 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
8936 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
8937 " Expected target-based directive.");
8938}
8939
Alexey Bataevc5687252019-03-21 19:35:27 +00008940bool CGOpenMPRuntime::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
8941 LangAS &AS) {
8942 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
8943 return false;
8944 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
8945 switch(A->getAllocatorType()) {
8946 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
8947 // Not supported, fallback to the default mem space.
8948 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
8949 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
8950 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
8951 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
8952 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
8953 case OMPAllocateDeclAttr::OMPConstMemAlloc:
8954 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
8955 AS = LangAS::Default;
8956 return true;
8957 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
8958 llvm_unreachable("Expected predefined allocator for the variables with the "
8959 "static storage.");
8960 }
8961 return false;
8962}
8963
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008964CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8965 CodeGenModule &CGM)
8966 : CGM(CGM) {
8967 if (CGM.getLangOpts().OpenMPIsDevice) {
8968 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8969 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8970 }
8971}
8972
8973CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8974 if (CGM.getLangOpts().OpenMPIsDevice)
8975 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8976}
8977
Alexey Bataev6d944102018-05-02 15:45:28 +00008978bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008979 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8980 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008981
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008982 StringRef Name = CGM.getMangledName(GD);
Alexey Bataev6d944102018-05-02 15:45:28 +00008983 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev34f8a702018-03-28 14:28:54 +00008984 // Do not to emit function if it is marked as declare target as it was already
8985 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008986 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008987 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
8988 if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008989 return !F->isDeclaration();
8990 return false;
8991 }
8992 return true;
8993 }
8994
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008995 return !AlreadyEmittedTargetFunctions.insert(Name).second;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008996}
8997
Samuel Antaoee8fb302016-01-06 13:42:12 +00008998llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8999 // If we have offloading in the current module, we need to emit the entries
9000 // now and register the offloading descriptor.
9001 createOffloadEntriesAndInfoMetadata();
9002
9003 // Create and register the offloading binary descriptors. This is the main
9004 // entity that captures all the information about offloading in the current
9005 // compilation unit.
9006 return createOffloadingBinaryDescriptorRegistration();
9007}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00009008
9009void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
9010 const OMPExecutableDirective &D,
9011 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00009012 llvm::Function *OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00009013 ArrayRef<llvm::Value *> CapturedVars) {
9014 if (!CGF.HaveInsertPoint())
9015 return;
9016
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009017 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00009018 CodeGenFunction::RunCleanupsScope Scope(CGF);
9019
9020 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
9021 llvm::Value *Args[] = {
9022 RTLoc,
9023 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
9024 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
9025 llvm::SmallVector<llvm::Value *, 16> RealArgs;
9026 RealArgs.append(std::begin(Args), std::end(Args));
9027 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
9028
James Y Knight9871db02019-02-05 16:42:33 +00009029 llvm::FunctionCallee RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00009030 CGF.EmitRuntimeCall(RTLFn, RealArgs);
9031}
9032
9033void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00009034 const Expr *NumTeams,
9035 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00009036 SourceLocation Loc) {
9037 if (!CGF.HaveInsertPoint())
9038 return;
9039
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009040 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00009041
Carlo Bertollic6872252016-04-04 15:55:02 +00009042 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009043 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00009044 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
9045 CGF.CGM.Int32Ty, /* isSigned = */ true)
9046 : CGF.Builder.getInt32(0);
9047
9048 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009049 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00009050 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
9051 CGF.CGM.Int32Ty, /* isSigned = */ true)
9052 : CGF.Builder.getInt32(0);
9053
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00009054 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00009055 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
9056 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00009057 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
9058 PushNumTeamsArgs);
9059}
Samuel Antaodf158d52016-04-27 22:58:19 +00009060
Samuel Antaocc10b852016-07-28 14:23:26 +00009061void CGOpenMPRuntime::emitTargetDataCalls(
9062 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9063 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00009064 if (!CGF.HaveInsertPoint())
9065 return;
9066
Samuel Antaocc10b852016-07-28 14:23:26 +00009067 // Action used to replace the default codegen action and turn privatization
9068 // off.
9069 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00009070
9071 // Generate the code for the opening of the data environment. Capture all the
9072 // arguments of the runtime call by reference because they are used in the
9073 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009074 auto &&BeginThenGen = [this, &D, Device, &Info,
9075 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00009076 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00009077 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00009078 MappableExprsHandler::MapValuesArrayTy Pointers;
9079 MappableExprsHandler::MapValuesArrayTy Sizes;
9080 MappableExprsHandler::MapFlagsArrayTy MapTypes;
9081
9082 // Get map clause information.
9083 MappableExprsHandler MCHandler(D, CGF);
9084 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00009085
9086 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00009087 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00009088
9089 llvm::Value *BasePointersArrayArg = nullptr;
9090 llvm::Value *PointersArrayArg = nullptr;
9091 llvm::Value *SizesArrayArg = nullptr;
9092 llvm::Value *MapTypesArrayArg = nullptr;
9093 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00009094 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00009095
9096 // Emit device ID if any.
9097 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009098 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00009099 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009100 CGF.Int64Ty, /*isSigned=*/true);
9101 } else {
9102 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9103 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009104
9105 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009106 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00009107
9108 llvm::Value *OffloadingArgs[] = {
9109 DeviceID, PointerNum, BasePointersArrayArg,
9110 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009111 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00009112 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00009113
9114 // If device pointer privatization is required, emit the body of the region
9115 // here. It will have to be duplicated: with and without privatization.
9116 if (!Info.CaptureDeviceAddrMap.empty())
9117 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009118 };
9119
9120 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009121 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
9122 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009123 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00009124
9125 llvm::Value *BasePointersArrayArg = nullptr;
9126 llvm::Value *PointersArrayArg = nullptr;
9127 llvm::Value *SizesArrayArg = nullptr;
9128 llvm::Value *MapTypesArrayArg = nullptr;
9129 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00009130 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00009131
9132 // Emit device ID if any.
9133 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009134 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00009135 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009136 CGF.Int64Ty, /*isSigned=*/true);
9137 } else {
9138 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9139 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009140
9141 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009142 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00009143
9144 llvm::Value *OffloadingArgs[] = {
9145 DeviceID, PointerNum, BasePointersArrayArg,
9146 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009147 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00009148 OffloadingArgs);
9149 };
9150
Samuel Antaocc10b852016-07-28 14:23:26 +00009151 // If we need device pointer privatization, we need to emit the body of the
9152 // region with no privatization in the 'else' branch of the conditional.
9153 // Otherwise, we don't have to do anything.
9154 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
9155 PrePostActionTy &) {
9156 if (!Info.CaptureDeviceAddrMap.empty()) {
9157 CodeGen.setAction(NoPrivAction);
9158 CodeGen(CGF);
9159 }
9160 };
9161
9162 // We don't have to do anything to close the region if the if clause evaluates
9163 // to false.
9164 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00009165
9166 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009167 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009168 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009169 RegionCodeGenTy RCG(BeginThenGen);
9170 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009171 }
9172
Samuel Antaocc10b852016-07-28 14:23:26 +00009173 // If we don't require privatization of device pointers, we emit the body in
9174 // between the runtime calls. This avoids duplicating the body code.
9175 if (Info.CaptureDeviceAddrMap.empty()) {
9176 CodeGen.setAction(NoPrivAction);
9177 CodeGen(CGF);
9178 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009179
9180 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009181 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009182 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009183 RegionCodeGenTy RCG(EndThenGen);
9184 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009185 }
9186}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009187
Samuel Antao8d2d7302016-05-26 18:30:22 +00009188void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00009189 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9190 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009191 if (!CGF.HaveInsertPoint())
9192 return;
9193
Samuel Antao8dd66282016-04-27 23:14:30 +00009194 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00009195 isa<OMPTargetExitDataDirective>(D) ||
9196 isa<OMPTargetUpdateDirective>(D)) &&
9197 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00009198
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009199 CodeGenFunction::OMPTargetDataInfo InputInfo;
9200 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009201 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009202 auto &&ThenGen = [this, &D, Device, &InputInfo,
9203 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009204 // Emit device ID if any.
9205 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009206 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009207 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009208 CGF.Int64Ty, /*isSigned=*/true);
9209 } else {
9210 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9211 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009212
9213 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009214 llvm::Constant *PointerNum =
9215 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009216
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009217 llvm::Value *OffloadingArgs[] = {DeviceID,
9218 PointerNum,
9219 InputInfo.BasePointersArray.getPointer(),
9220 InputInfo.PointersArray.getPointer(),
9221 InputInfo.SizesArray.getPointer(),
9222 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00009223
Samuel Antao8d2d7302016-05-26 18:30:22 +00009224 // Select the right runtime function call for each expected standalone
9225 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009226 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00009227 OpenMPRTLFunction RTLFn;
9228 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00009229 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009230 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
9231 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009232 break;
9233 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009234 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
9235 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009236 break;
9237 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009238 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
9239 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009240 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009241 case OMPD_parallel:
9242 case OMPD_for:
9243 case OMPD_parallel_for:
9244 case OMPD_parallel_sections:
9245 case OMPD_for_simd:
9246 case OMPD_parallel_for_simd:
9247 case OMPD_cancel:
9248 case OMPD_cancellation_point:
9249 case OMPD_ordered:
9250 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009251 case OMPD_allocate:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009252 case OMPD_task:
9253 case OMPD_simd:
9254 case OMPD_sections:
9255 case OMPD_section:
9256 case OMPD_single:
9257 case OMPD_master:
9258 case OMPD_critical:
9259 case OMPD_taskyield:
9260 case OMPD_barrier:
9261 case OMPD_taskwait:
9262 case OMPD_taskgroup:
9263 case OMPD_atomic:
9264 case OMPD_flush:
9265 case OMPD_teams:
9266 case OMPD_target_data:
9267 case OMPD_distribute:
9268 case OMPD_distribute_simd:
9269 case OMPD_distribute_parallel_for:
9270 case OMPD_distribute_parallel_for_simd:
9271 case OMPD_teams_distribute:
9272 case OMPD_teams_distribute_simd:
9273 case OMPD_teams_distribute_parallel_for:
9274 case OMPD_teams_distribute_parallel_for_simd:
9275 case OMPD_declare_simd:
9276 case OMPD_declare_target:
9277 case OMPD_end_declare_target:
9278 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009279 case OMPD_declare_mapper:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009280 case OMPD_taskloop:
9281 case OMPD_taskloop_simd:
9282 case OMPD_target:
9283 case OMPD_target_simd:
9284 case OMPD_target_teams_distribute:
9285 case OMPD_target_teams_distribute_simd:
9286 case OMPD_target_teams_distribute_parallel_for:
9287 case OMPD_target_teams_distribute_parallel_for_simd:
9288 case OMPD_target_teams:
9289 case OMPD_target_parallel:
9290 case OMPD_target_parallel_for:
9291 case OMPD_target_parallel_for_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009292 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009293 case OMPD_unknown:
9294 llvm_unreachable("Unexpected standalone target data directive.");
9295 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009296 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009297 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009298 };
9299
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009300 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
9301 CodeGenFunction &CGF, PrePostActionTy &) {
9302 // Fill up the arrays with all the mapped variables.
9303 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
9304 MappableExprsHandler::MapValuesArrayTy Pointers;
9305 MappableExprsHandler::MapValuesArrayTy Sizes;
9306 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009307
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009308 // Get map clause information.
9309 MappableExprsHandler MEHandler(D, CGF);
9310 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
9311
9312 TargetDataInfo Info;
9313 // Fill up the arrays and create the arguments.
9314 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
9315 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
9316 Info.PointersArray, Info.SizesArray,
9317 Info.MapTypesArray, Info);
9318 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
9319 InputInfo.BasePointersArray =
9320 Address(Info.BasePointersArray, CGM.getPointerAlign());
9321 InputInfo.PointersArray =
9322 Address(Info.PointersArray, CGM.getPointerAlign());
9323 InputInfo.SizesArray =
9324 Address(Info.SizesArray, CGM.getPointerAlign());
9325 MapTypesArray = Info.MapTypesArray;
9326 if (D.hasClausesOfKind<OMPDependClause>())
9327 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
9328 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00009329 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009330 };
9331
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009332 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009333 emitOMPIfClause(CGF, IfCond, TargetThenGen,
9334 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009335 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009336 RegionCodeGenTy ThenRCG(TargetThenGen);
9337 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009338 }
9339}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009340
9341namespace {
9342 /// Kind of parameter in a function with 'declare simd' directive.
9343 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
9344 /// Attribute set of the parameter.
9345 struct ParamAttrTy {
9346 ParamKindTy Kind = Vector;
9347 llvm::APSInt StrideOrArg;
9348 llvm::APSInt Alignment;
9349 };
9350} // namespace
9351
9352static unsigned evaluateCDTSize(const FunctionDecl *FD,
9353 ArrayRef<ParamAttrTy> ParamAttrs) {
9354 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
9355 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
9356 // of that clause. The VLEN value must be power of 2.
9357 // In other case the notion of the function`s "characteristic data type" (CDT)
9358 // is used to compute the vector length.
9359 // CDT is defined in the following order:
9360 // a) For non-void function, the CDT is the return type.
9361 // b) If the function has any non-uniform, non-linear parameters, then the
9362 // CDT is the type of the first such parameter.
9363 // c) If the CDT determined by a) or b) above is struct, union, or class
9364 // type which is pass-by-value (except for the type that maps to the
9365 // built-in complex data type), the characteristic data type is int.
9366 // d) If none of the above three cases is applicable, the CDT is int.
9367 // The VLEN is then determined based on the CDT and the size of vector
9368 // register of that ISA for which current vector version is generated. The
9369 // VLEN is computed using the formula below:
9370 // VLEN = sizeof(vector_register) / sizeof(CDT),
9371 // where vector register size specified in section 3.2.1 Registers and the
9372 // Stack Frame of original AMD64 ABI document.
9373 QualType RetType = FD->getReturnType();
9374 if (RetType.isNull())
9375 return 0;
9376 ASTContext &C = FD->getASTContext();
9377 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009378 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009379 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009380 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009381 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009382 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009383 if (ParamAttrs[Offset].Kind == Vector)
9384 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
9385 ++Offset;
9386 }
9387 if (CDT.isNull()) {
9388 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
9389 if (ParamAttrs[I + Offset].Kind == Vector) {
9390 CDT = FD->getParamDecl(I)->getType();
9391 break;
9392 }
9393 }
9394 }
9395 }
9396 if (CDT.isNull())
9397 CDT = C.IntTy;
9398 CDT = CDT->getCanonicalTypeUnqualified();
9399 if (CDT->isRecordType() || CDT->isUnionType())
9400 CDT = C.IntTy;
9401 return C.getTypeSize(CDT);
9402}
9403
9404static void
9405emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00009406 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009407 ArrayRef<ParamAttrTy> ParamAttrs,
9408 OMPDeclareSimdDeclAttr::BranchStateTy State) {
9409 struct ISADataTy {
9410 char ISA;
9411 unsigned VecRegSize;
9412 };
9413 ISADataTy ISAData[] = {
9414 {
9415 'b', 128
9416 }, // SSE
9417 {
9418 'c', 256
9419 }, // AVX
9420 {
9421 'd', 256
9422 }, // AVX2
9423 {
9424 'e', 512
9425 }, // AVX512
9426 };
9427 llvm::SmallVector<char, 2> Masked;
9428 switch (State) {
9429 case OMPDeclareSimdDeclAttr::BS_Undefined:
9430 Masked.push_back('N');
9431 Masked.push_back('M');
9432 break;
9433 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
9434 Masked.push_back('N');
9435 break;
9436 case OMPDeclareSimdDeclAttr::BS_Inbranch:
9437 Masked.push_back('M');
9438 break;
9439 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009440 for (char Mask : Masked) {
9441 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009442 SmallString<256> Buffer;
9443 llvm::raw_svector_ostream Out(Buffer);
9444 Out << "_ZGV" << Data.ISA << Mask;
9445 if (!VLENVal) {
9446 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
9447 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009448 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009449 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009450 }
9451 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009452 switch (ParamAttr.Kind){
9453 case LinearWithVarStride:
9454 Out << 's' << ParamAttr.StrideOrArg;
9455 break;
9456 case Linear:
9457 Out << 'l';
9458 if (!!ParamAttr.StrideOrArg)
9459 Out << ParamAttr.StrideOrArg;
9460 break;
9461 case Uniform:
9462 Out << 'u';
9463 break;
9464 case Vector:
9465 Out << 'v';
9466 break;
9467 }
9468 if (!!ParamAttr.Alignment)
9469 Out << 'a' << ParamAttr.Alignment;
9470 }
9471 Out << '_' << Fn->getName();
9472 Fn->addFnAttr(Out.str());
9473 }
9474 }
9475}
9476
9477void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
9478 llvm::Function *Fn) {
9479 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009480 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009481 // Map params to their positions in function decl.
9482 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
9483 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009484 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009485 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009486 for (const ParmVarDecl *P : FD->parameters()) {
9487 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009488 ++ParamPos;
9489 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009490 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009491 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009492 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
9493 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009494 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009495 E = E->IgnoreParenImpCasts();
9496 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009497 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009498 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009499 } else {
9500 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9501 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009502 Pos = ParamPositions[PVD];
9503 }
9504 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009505 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009506 // Get alignment info.
9507 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009508 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009509 E = E->IgnoreParenImpCasts();
9510 unsigned Pos;
9511 QualType ParmTy;
9512 if (isa<CXXThisExpr>(E)) {
9513 Pos = ParamPositions[FD];
9514 ParmTy = E->getType();
9515 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009516 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9517 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009518 Pos = ParamPositions[PVD];
9519 ParmTy = PVD->getType();
9520 }
9521 ParamAttrs[Pos].Alignment =
9522 (*NI)
9523 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009524 : llvm::APSInt::getUnsigned(
9525 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
9526 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009527 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009528 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009529 // Mark linear parameters.
9530 auto SI = Attr->steps_begin();
9531 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009532 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009533 E = E->IgnoreParenImpCasts();
9534 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009535 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009536 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009537 } else {
9538 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9539 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009540 Pos = ParamPositions[PVD];
9541 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009542 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009543 ParamAttr.Kind = Linear;
9544 if (*SI) {
Fangrui Song407659a2018-11-30 23:41:18 +00009545 Expr::EvalResult Result;
9546 if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009547 if (const auto *DRE =
9548 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9549 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009550 ParamAttr.Kind = LinearWithVarStride;
9551 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9552 ParamPositions[StridePVD->getCanonicalDecl()]);
9553 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009554 }
Fangrui Song407659a2018-11-30 23:41:18 +00009555 } else {
9556 ParamAttr.StrideOrArg = Result.Val.getInt();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009557 }
9558 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009559 ++SI;
9560 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009561 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009562 llvm::APSInt VLENVal;
9563 if (const Expr *VLEN = Attr->getSimdlen())
9564 VLENVal = VLEN->EvaluateKnownConstInt(C);
9565 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9566 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9567 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9568 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009569 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009570 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009571 }
9572}
Alexey Bataev8b427062016-05-25 12:36:08 +00009573
9574namespace {
9575/// Cleanup action for doacross support.
9576class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9577public:
9578 static const int DoacrossFinArgs = 2;
9579
9580private:
James Y Knight9871db02019-02-05 16:42:33 +00009581 llvm::FunctionCallee RTLFn;
Alexey Bataev8b427062016-05-25 12:36:08 +00009582 llvm::Value *Args[DoacrossFinArgs];
9583
9584public:
James Y Knight9871db02019-02-05 16:42:33 +00009585 DoacrossCleanupTy(llvm::FunctionCallee RTLFn,
9586 ArrayRef<llvm::Value *> CallArgs)
Alexey Bataev8b427062016-05-25 12:36:08 +00009587 : RTLFn(RTLFn) {
9588 assert(CallArgs.size() == DoacrossFinArgs);
9589 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9590 }
9591 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9592 if (!CGF.HaveInsertPoint())
9593 return;
9594 CGF.EmitRuntimeCall(RTLFn, Args);
9595 }
9596};
9597} // namespace
9598
9599void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009600 const OMPLoopDirective &D,
9601 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009602 if (!CGF.HaveInsertPoint())
9603 return;
9604
9605 ASTContext &C = CGM.getContext();
9606 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9607 RecordDecl *RD;
9608 if (KmpDimTy.isNull()) {
9609 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9610 // kmp_int64 lo; // lower
9611 // kmp_int64 up; // upper
9612 // kmp_int64 st; // stride
9613 // };
9614 RD = C.buildImplicitRecord("kmp_dim");
9615 RD->startDefinition();
9616 addFieldToRecordDecl(C, RD, Int64Ty);
9617 addFieldToRecordDecl(C, RD, Int64Ty);
9618 addFieldToRecordDecl(C, RD, Int64Ty);
9619 RD->completeDefinition();
9620 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009621 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009622 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009623 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009624 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9625 QualType ArrayTy =
9626 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009627
Alexey Bataevf138fda2018-08-13 19:04:24 +00009628 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9629 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009630 enum { LowerFD = 0, UpperFD, StrideFD };
9631 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009632 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
James Y Knight751fe282019-02-09 22:22:28 +00009633 LValue DimsLVal = CGF.MakeAddrLValue(
9634 CGF.Builder.CreateConstArrayGEP(DimsAddr, I), KmpDimTy);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009635 // dims.upper = num_iterations;
9636 LValue UpperLVal = CGF.EmitLValueForField(
9637 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9638 llvm::Value *NumIterVal =
9639 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9640 D.getNumIterations()->getType(), Int64Ty,
9641 D.getNumIterations()->getExprLoc());
9642 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9643 // dims.stride = 1;
9644 LValue StrideLVal = CGF.EmitLValueForField(
9645 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9646 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9647 StrideLVal);
9648 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009649
9650 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9651 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009652 llvm::Value *Args[] = {
9653 emitUpdateLocation(CGF, D.getBeginLoc()),
9654 getThreadID(CGF, D.getBeginLoc()),
9655 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9656 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00009657 CGF.Builder.CreateConstArrayGEP(DimsAddr, 0).getPointer(),
Alexey Bataevf138fda2018-08-13 19:04:24 +00009658 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009659
James Y Knight9871db02019-02-05 16:42:33 +00009660 llvm::FunctionCallee RTLFn =
9661 createRuntimeFunction(OMPRTL__kmpc_doacross_init);
Alexey Bataev8b427062016-05-25 12:36:08 +00009662 CGF.EmitRuntimeCall(RTLFn, Args);
9663 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009664 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
James Y Knight9871db02019-02-05 16:42:33 +00009665 llvm::FunctionCallee FiniRTLFn =
9666 createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
Alexey Bataev8b427062016-05-25 12:36:08 +00009667 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9668 llvm::makeArrayRef(FiniArgs));
9669}
9670
9671void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9672 const OMPDependClause *C) {
9673 QualType Int64Ty =
9674 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009675 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9676 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9677 Int64Ty, Size, ArrayType::Normal, 0);
9678 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9679 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9680 const Expr *CounterVal = C->getLoopData(I);
9681 assert(CounterVal);
9682 llvm::Value *CntVal = CGF.EmitScalarConversion(
9683 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9684 CounterVal->getExprLoc());
James Y Knight751fe282019-02-09 22:22:28 +00009685 CGF.EmitStoreOfScalar(CntVal, CGF.Builder.CreateConstArrayGEP(CntAddr, I),
9686 /*Volatile=*/false, Int64Ty);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009687 }
9688 llvm::Value *Args[] = {
9689 emitUpdateLocation(CGF, C->getBeginLoc()),
9690 getThreadID(CGF, C->getBeginLoc()),
James Y Knight751fe282019-02-09 22:22:28 +00009691 CGF.Builder.CreateConstArrayGEP(CntAddr, 0).getPointer()};
James Y Knight9871db02019-02-05 16:42:33 +00009692 llvm::FunctionCallee RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009693 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009694 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009695 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009696 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9697 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9698 }
9699 CGF.EmitRuntimeCall(RTLFn, Args);
9700}
9701
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009702void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00009703 llvm::FunctionCallee Callee,
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009704 ArrayRef<llvm::Value *> Args) const {
9705 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009706 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9707
James Y Knight9871db02019-02-05 16:42:33 +00009708 if (auto *Fn = dyn_cast<llvm::Function>(Callee.getCallee())) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009709 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009710 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009711 return;
9712 }
9713 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009714 CGF.EmitRuntimeCall(Callee, Args);
9715}
9716
9717void CGOpenMPRuntime::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00009718 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3c595a62017-08-14 15:01:03 +00009719 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009720 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009721}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009722
9723Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9724 const VarDecl *NativeParam,
9725 const VarDecl *TargetParam) const {
9726 return CGF.GetAddrOfLocalVar(NativeParam);
9727}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009728
Alexey Bataev4f680db2019-03-19 16:41:16 +00009729namespace {
9730/// Cleanup action for allocate support.
9731class OMPAllocateCleanupTy final : public EHScopeStack::Cleanup {
9732public:
9733 static const int CleanupArgs = 3;
9734
9735private:
9736 llvm::FunctionCallee RTLFn;
9737 llvm::Value *Args[CleanupArgs];
9738
9739public:
9740 OMPAllocateCleanupTy(llvm::FunctionCallee RTLFn,
9741 ArrayRef<llvm::Value *> CallArgs)
9742 : RTLFn(RTLFn) {
9743 assert(CallArgs.size() == CleanupArgs &&
9744 "Size of arguments does not match.");
9745 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9746 }
9747 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9748 if (!CGF.HaveInsertPoint())
9749 return;
9750 CGF.EmitRuntimeCall(RTLFn, Args);
9751 }
9752};
9753} // namespace
9754
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009755Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9756 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00009757 if (!VD)
9758 return Address::invalid();
Alexey Bataev4f680db2019-03-19 16:41:16 +00009759 const VarDecl *CVD = VD->getCanonicalDecl();
9760 if (!CVD->hasAttr<OMPAllocateDeclAttr>())
9761 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00009762 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
9763 // Use the default allocation.
Alexey Bataev0fd3c682019-04-02 19:44:46 +00009764 if (AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc &&
9765 !AA->getAllocator())
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00009766 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00009767 llvm::Value *Size;
9768 CharUnits Align = CGM.getContext().getDeclAlign(CVD);
9769 if (CVD->getType()->isVariablyModifiedType()) {
9770 Size = CGF.getTypeSize(CVD->getType());
Alexey Bataev9c397812019-04-03 17:57:06 +00009771 // Align the size: ((size + align - 1) / align) * align
9772 Size = CGF.Builder.CreateNUWAdd(
9773 Size, CGM.getSize(Align - CharUnits::fromQuantity(1)));
9774 Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align));
9775 Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align));
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00009776 } else {
9777 CharUnits Sz = CGM.getContext().getTypeSizeInChars(CVD->getType());
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00009778 Size = CGM.getSize(Sz.alignTo(Align));
Alexey Bataev4f680db2019-03-19 16:41:16 +00009779 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00009780 llvm::Value *ThreadID = getThreadID(CGF, CVD->getBeginLoc());
9781 assert(AA->getAllocator() &&
9782 "Expected allocator expression for non-default allocator.");
9783 llvm::Value *Allocator = CGF.EmitScalarExpr(AA->getAllocator());
9784 llvm::Value *Args[] = {ThreadID, Size, Allocator};
9785
9786 llvm::Value *Addr =
9787 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_alloc), Args,
9788 CVD->getName() + ".void.addr");
9789 llvm::Value *FiniArgs[OMPAllocateCleanupTy::CleanupArgs] = {ThreadID, Addr,
9790 Allocator};
9791 llvm::FunctionCallee FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_free);
9792
9793 CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9794 llvm::makeArrayRef(FiniArgs));
9795 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
9796 Addr,
9797 CGF.ConvertTypeForMem(CGM.getContext().getPointerType(CVD->getType())),
9798 CVD->getName() + ".addr");
9799 return Address(Addr, Align);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009800}
9801
James Y Knight9871db02019-02-05 16:42:33 +00009802llvm::Function *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009803 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9804 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9805 llvm_unreachable("Not supported in SIMD-only mode");
9806}
9807
James Y Knight9871db02019-02-05 16:42:33 +00009808llvm::Function *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009809 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9810 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9811 llvm_unreachable("Not supported in SIMD-only mode");
9812}
9813
James Y Knight9871db02019-02-05 16:42:33 +00009814llvm::Function *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009815 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9816 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9817 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9818 bool Tied, unsigned &NumberOfParts) {
9819 llvm_unreachable("Not supported in SIMD-only mode");
9820}
9821
9822void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9823 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00009824 llvm::Function *OutlinedFn,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009825 ArrayRef<llvm::Value *> CapturedVars,
9826 const Expr *IfCond) {
9827 llvm_unreachable("Not supported in SIMD-only mode");
9828}
9829
9830void CGOpenMPSIMDRuntime::emitCriticalRegion(
9831 CodeGenFunction &CGF, StringRef CriticalName,
9832 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9833 const Expr *Hint) {
9834 llvm_unreachable("Not supported in SIMD-only mode");
9835}
9836
9837void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9838 const RegionCodeGenTy &MasterOpGen,
9839 SourceLocation Loc) {
9840 llvm_unreachable("Not supported in SIMD-only mode");
9841}
9842
9843void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9844 SourceLocation Loc) {
9845 llvm_unreachable("Not supported in SIMD-only mode");
9846}
9847
9848void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9849 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9850 SourceLocation Loc) {
9851 llvm_unreachable("Not supported in SIMD-only mode");
9852}
9853
9854void CGOpenMPSIMDRuntime::emitSingleRegion(
9855 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9856 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9857 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9858 ArrayRef<const Expr *> AssignmentOps) {
9859 llvm_unreachable("Not supported in SIMD-only mode");
9860}
9861
9862void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9863 const RegionCodeGenTy &OrderedOpGen,
9864 SourceLocation Loc,
9865 bool IsThreads) {
9866 llvm_unreachable("Not supported in SIMD-only mode");
9867}
9868
9869void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9870 SourceLocation Loc,
9871 OpenMPDirectiveKind Kind,
9872 bool EmitChecks,
9873 bool ForceSimpleCall) {
9874 llvm_unreachable("Not supported in SIMD-only mode");
9875}
9876
9877void CGOpenMPSIMDRuntime::emitForDispatchInit(
9878 CodeGenFunction &CGF, SourceLocation Loc,
9879 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9880 bool Ordered, const DispatchRTInput &DispatchValues) {
9881 llvm_unreachable("Not supported in SIMD-only mode");
9882}
9883
9884void CGOpenMPSIMDRuntime::emitForStaticInit(
9885 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9886 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9887 llvm_unreachable("Not supported in SIMD-only mode");
9888}
9889
9890void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9891 CodeGenFunction &CGF, SourceLocation Loc,
9892 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9893 llvm_unreachable("Not supported in SIMD-only mode");
9894}
9895
9896void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9897 SourceLocation Loc,
9898 unsigned IVSize,
9899 bool IVSigned) {
9900 llvm_unreachable("Not supported in SIMD-only mode");
9901}
9902
9903void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9904 SourceLocation Loc,
9905 OpenMPDirectiveKind DKind) {
9906 llvm_unreachable("Not supported in SIMD-only mode");
9907}
9908
9909llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9910 SourceLocation Loc,
9911 unsigned IVSize, bool IVSigned,
9912 Address IL, Address LB,
9913 Address UB, Address ST) {
9914 llvm_unreachable("Not supported in SIMD-only mode");
9915}
9916
9917void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9918 llvm::Value *NumThreads,
9919 SourceLocation Loc) {
9920 llvm_unreachable("Not supported in SIMD-only mode");
9921}
9922
9923void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9924 OpenMPProcBindClauseKind ProcBind,
9925 SourceLocation Loc) {
9926 llvm_unreachable("Not supported in SIMD-only mode");
9927}
9928
9929Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9930 const VarDecl *VD,
9931 Address VDAddr,
9932 SourceLocation Loc) {
9933 llvm_unreachable("Not supported in SIMD-only mode");
9934}
9935
9936llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9937 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9938 CodeGenFunction *CGF) {
9939 llvm_unreachable("Not supported in SIMD-only mode");
9940}
9941
9942Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9943 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9944 llvm_unreachable("Not supported in SIMD-only mode");
9945}
9946
9947void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9948 ArrayRef<const Expr *> Vars,
9949 SourceLocation Loc) {
9950 llvm_unreachable("Not supported in SIMD-only mode");
9951}
9952
9953void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9954 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00009955 llvm::Function *TaskFunction,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009956 QualType SharedsTy, Address Shareds,
9957 const Expr *IfCond,
9958 const OMPTaskDataTy &Data) {
9959 llvm_unreachable("Not supported in SIMD-only mode");
9960}
9961
9962void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9963 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00009964 llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009965 const Expr *IfCond, const OMPTaskDataTy &Data) {
9966 llvm_unreachable("Not supported in SIMD-only mode");
9967}
9968
9969void CGOpenMPSIMDRuntime::emitReduction(
9970 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9971 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9972 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9973 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9974 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9975 ReductionOps, Options);
9976}
9977
9978llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9979 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9980 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9981 llvm_unreachable("Not supported in SIMD-only mode");
9982}
9983
9984void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9985 SourceLocation Loc,
9986 ReductionCodeGen &RCG,
9987 unsigned N) {
9988 llvm_unreachable("Not supported in SIMD-only mode");
9989}
9990
9991Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9992 SourceLocation Loc,
9993 llvm::Value *ReductionsPtr,
9994 LValue SharedLVal) {
9995 llvm_unreachable("Not supported in SIMD-only mode");
9996}
9997
9998void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9999 SourceLocation Loc) {
10000 llvm_unreachable("Not supported in SIMD-only mode");
10001}
10002
10003void CGOpenMPSIMDRuntime::emitCancellationPointCall(
10004 CodeGenFunction &CGF, SourceLocation Loc,
10005 OpenMPDirectiveKind CancelRegion) {
10006 llvm_unreachable("Not supported in SIMD-only mode");
10007}
10008
10009void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
10010 SourceLocation Loc, const Expr *IfCond,
10011 OpenMPDirectiveKind CancelRegion) {
10012 llvm_unreachable("Not supported in SIMD-only mode");
10013}
10014
10015void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
10016 const OMPExecutableDirective &D, StringRef ParentName,
10017 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
10018 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
10019 llvm_unreachable("Not supported in SIMD-only mode");
10020}
10021
10022void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
10023 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +000010024 llvm::Function *OutlinedFn,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +000010025 llvm::Value *OutlinedFnID,
James Y Knight9871db02019-02-05 16:42:33 +000010026 const Expr *IfCond,
10027 const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +000010028 llvm_unreachable("Not supported in SIMD-only mode");
10029}
10030
10031bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
10032 llvm_unreachable("Not supported in SIMD-only mode");
10033}
10034
10035bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
10036 llvm_unreachable("Not supported in SIMD-only mode");
10037}
10038
10039bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
10040 return false;
10041}
10042
10043llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
10044 return nullptr;
10045}
10046
10047void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
10048 const OMPExecutableDirective &D,
10049 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +000010050 llvm::Function *OutlinedFn,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +000010051 ArrayRef<llvm::Value *> CapturedVars) {
10052 llvm_unreachable("Not supported in SIMD-only mode");
10053}
10054
10055void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
10056 const Expr *NumTeams,
10057 const Expr *ThreadLimit,
10058 SourceLocation Loc) {
10059 llvm_unreachable("Not supported in SIMD-only mode");
10060}
10061
10062void CGOpenMPSIMDRuntime::emitTargetDataCalls(
10063 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
10064 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
10065 llvm_unreachable("Not supported in SIMD-only mode");
10066}
10067
10068void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
10069 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
10070 const Expr *Device) {
10071 llvm_unreachable("Not supported in SIMD-only mode");
10072}
10073
10074void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +000010075 const OMPLoopDirective &D,
10076 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +000010077 llvm_unreachable("Not supported in SIMD-only mode");
10078}
10079
10080void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
10081 const OMPDependClause *C) {
10082 llvm_unreachable("Not supported in SIMD-only mode");
10083}
10084
10085const VarDecl *
10086CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
10087 const VarDecl *NativeParam) const {
10088 llvm_unreachable("Not supported in SIMD-only mode");
10089}
10090
10091Address
10092CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
10093 const VarDecl *NativeParam,
10094 const VarDecl *TargetParam) const {
10095 llvm_unreachable("Not supported in SIMD-only mode");
10096}