blob: 42f1ceac673d578058e5a350a3d95c29d6cc4502 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +000017#include "CGRecordLayout.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000019#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000023#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000024#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000025#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000029#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000030#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000031#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000032
33using namespace clang;
34using namespace CodeGen;
35
Benjamin Kramerc52193f2014-10-10 13:57:57 +000036namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037/// Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000038class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
39public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000040 /// Kinds of OpenMP regions used in codegen.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000041 enum CGOpenMPRegionKind {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// Region with outlined function for standalone 'parallel'
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000043 /// directive.
44 ParallelOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Region with outlined function for standalone 'task' directive.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 TaskOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000047 /// Region for constructs that do not require function outlining,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000048 /// like 'for', 'sections', 'atomic' etc. directives.
49 InlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000050 /// Region with outlined function for standalone 'target' directive.
Samuel Antaobed3c462015-10-02 16:14:20 +000051 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 };
Alexey Bataev18095712014-10-10 12:19:54 +000053
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000054 CGOpenMPRegionInfo(const CapturedStmt &CS,
55 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
57 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000060
61 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
63 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000064 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000065 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000067 /// Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000068 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000069 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000072 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000073
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000074 /// Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000075 /// \return LValue for thread id variable. This LValue always has type int32*.
76 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000077
Alexey Bataev48591dd2016-04-20 04:01:36 +000078 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
79
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000080 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000081
Alexey Bataev81c7ea02015-07-03 09:56:58 +000082 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
83
Alexey Bataev25e5b442015-09-15 12:52:43 +000084 bool hasCancel() const { return HasCancel; }
85
Alexey Bataev18095712014-10-10 12:19:54 +000086 static bool classof(const CGCapturedStmtInfo *Info) {
87 return Info->getKind() == CR_OpenMP;
88 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000089
Alexey Bataev48591dd2016-04-20 04:01:36 +000090 ~CGOpenMPRegionInfo() override = default;
91
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000092protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000093 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000094 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000095 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000096 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000097};
Alexey Bataev18095712014-10-10 12:19:54 +000098
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000099/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000100class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000101public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000102 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000103 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000104 OpenMPDirectiveKind Kind, bool HasCancel,
105 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000106 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
107 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000109 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
110 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000111
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000112 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000113 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000114 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000115
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000116 /// Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000117 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000118
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000119 static bool classof(const CGCapturedStmtInfo *Info) {
120 return CGOpenMPRegionInfo::classof(Info) &&
121 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
122 ParallelOutlinedRegion;
123 }
124
Alexey Bataev18095712014-10-10 12:19:54 +0000125private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000126 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev18095712014-10-10 12:19:54 +0000127 /// constructs.
128 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000129 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000130};
131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000132/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000134public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000135 class UntiedTaskActionTy final : public PrePostActionTy {
136 bool Untied;
137 const VarDecl *PartIDVar;
138 const RegionCodeGenTy UntiedCodeGen;
139 llvm::SwitchInst *UntiedSwitch = nullptr;
140
141 public:
142 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
143 const RegionCodeGenTy &UntiedCodeGen)
144 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
145 void Enter(CodeGenFunction &CGF) override {
146 if (Untied) {
147 // Emit task switching point.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000148 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000149 CGF.GetAddrOfLocalVar(PartIDVar),
150 PartIDVar->getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000151 llvm::Value *Res =
152 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
153 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
Alexey Bataev48591dd2016-04-20 04:01:36 +0000154 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
155 CGF.EmitBlock(DoneBB);
156 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
157 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
158 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
159 CGF.Builder.GetInsertBlock());
160 emitUntiedSwitch(CGF);
161 }
162 }
163 void emitUntiedSwitch(CodeGenFunction &CGF) const {
164 if (Untied) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000165 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000166 CGF.GetAddrOfLocalVar(PartIDVar),
167 PartIDVar->getType()->castAs<PointerType>());
168 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
169 PartIdLVal);
170 UntiedCodeGen(CGF);
171 CodeGenFunction::JumpDest CurPoint =
172 CGF.getJumpDestInCurrentScope(".untied.next.");
173 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
174 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
175 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
176 CGF.Builder.GetInsertBlock());
177 CGF.EmitBranchThroughCleanup(CurPoint);
178 CGF.EmitBlock(CurPoint.getBlock());
179 }
180 }
181 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
182 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000183 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000184 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000185 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000186 OpenMPDirectiveKind Kind, bool HasCancel,
187 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000188 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000189 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
191 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000192
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000193 /// Get a variable or parameter for storing global thread id
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000195 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000197 /// Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000198 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000199
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000200 /// Get the name of the capture helper.
Alexey Bataev62b63b12015-03-10 07:28:44 +0000201 StringRef getHelperName() const override { return ".omp_outlined."; }
202
Alexey Bataev48591dd2016-04-20 04:01:36 +0000203 void emitUntiedSwitch(CodeGenFunction &CGF) override {
204 Action.emitUntiedSwitch(CGF);
205 }
206
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000207 static bool classof(const CGCapturedStmtInfo *Info) {
208 return CGOpenMPRegionInfo::classof(Info) &&
209 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
210 TaskOutlinedRegion;
211 }
212
Alexey Bataev62b63b12015-03-10 07:28:44 +0000213private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000214 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev62b63b12015-03-10 07:28:44 +0000215 /// constructs.
216 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000217 /// Action for emitting code for untied tasks.
218 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000219};
220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221/// API for inlined captured statement code generation in OpenMP
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000222/// constructs.
223class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
224public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000225 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000226 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000227 OpenMPDirectiveKind Kind, bool HasCancel)
228 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
229 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000231
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000232 // Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000233 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000234 if (OuterRegionInfo)
235 return OuterRegionInfo->getContextValue();
236 llvm_unreachable("No context value for inlined OpenMP region");
237 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000238
Hans Wennborg7eb54642015-09-10 17:07:54 +0000239 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000240 if (OuterRegionInfo) {
241 OuterRegionInfo->setContextValue(V);
242 return;
243 }
244 llvm_unreachable("No context value for inlined OpenMP region");
245 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000247 /// Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000248 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000249 if (OuterRegionInfo)
250 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000251 // If there is no outer outlined region,no need to lookup in a list of
252 // captured variables, we can use the original one.
253 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000254 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000255
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000256 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000257 if (OuterRegionInfo)
258 return OuterRegionInfo->getThisFieldDecl();
259 return nullptr;
260 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000262 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000264 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000265 if (OuterRegionInfo)
266 return OuterRegionInfo->getThreadIDVariable();
267 return nullptr;
268 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000269
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000270 /// Get an LValue for the current ThreadID variable.
Alexey Bataev311a9282017-10-12 13:51:32 +0000271 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
272 if (OuterRegionInfo)
273 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
274 llvm_unreachable("No LValue for inlined OpenMP construct");
275 }
276
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000277 /// Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000278 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000279 if (auto *OuterRegionInfo = getOldCSI())
280 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000281 llvm_unreachable("No helper name for inlined OpenMP construct");
282 }
283
Alexey Bataev48591dd2016-04-20 04:01:36 +0000284 void emitUntiedSwitch(CodeGenFunction &CGF) override {
285 if (OuterRegionInfo)
286 OuterRegionInfo->emitUntiedSwitch(CGF);
287 }
288
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000289 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
290
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000291 static bool classof(const CGCapturedStmtInfo *Info) {
292 return CGOpenMPRegionInfo::classof(Info) &&
293 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
294 }
295
Alexey Bataev48591dd2016-04-20 04:01:36 +0000296 ~CGOpenMPInlinedRegionInfo() override = default;
297
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000298private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000299 /// CodeGen info about outer OpenMP region.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000300 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
301 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000302};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000304/// API for captured statement code generation in OpenMP target
Samuel Antaobed3c462015-10-02 16:14:20 +0000305/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000306/// captured fields. The name of the target region has to be unique in a given
307/// application so it is provided by the client, because only the client has
308/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000309class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000310public:
311 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000313 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000314 /*HasCancel=*/false),
315 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000317 /// This is unused for target regions because each starts executing
Samuel Antaobed3c462015-10-02 16:14:20 +0000318 /// with a single thread.
319 const VarDecl *getThreadIDVariable() const override { return nullptr; }
320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000321 /// Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000322 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000323
324 static bool classof(const CGCapturedStmtInfo *Info) {
325 return CGOpenMPRegionInfo::classof(Info) &&
326 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
327 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000328
329private:
330 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000331};
332
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000333static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000334 llvm_unreachable("No codegen for expressions");
335}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000336/// API for generation of expressions captured in a innermost OpenMP
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000338class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000339public:
340 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
341 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
342 OMPD_unknown,
343 /*HasCancel=*/false),
344 PrivScope(CGF) {
345 // Make sure the globals captured in the provided statement are local by
346 // using the privatization logic. We assume the same variable is not
347 // captured more than once.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000348 for (const auto &C : CS.captures()) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000349 if (!C.capturesVariable() && !C.capturesVariableByCopy())
350 continue;
351
352 const VarDecl *VD = C.getCapturedVar();
353 if (VD->isLocalVarDeclOrParm())
354 continue;
355
356 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
357 /*RefersToEnclosingVariableOrCapture=*/false,
358 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000359 C.getLocation());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000360 PrivScope.addPrivate(
361 VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
Samuel Antaob68e2db2016-03-03 16:20:23 +0000362 }
363 (void)PrivScope.Privatize();
364 }
365
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000366 /// Lookup the captured field decl for a variable.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000367 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000368 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
Samuel Antaob68e2db2016-03-03 16:20:23 +0000369 return FD;
370 return nullptr;
371 }
372
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000373 /// Emit the captured statement body.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000374 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
375 llvm_unreachable("No body for expressions");
376 }
377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000378 /// Get a variable or parameter for storing global thread id
Samuel Antaob68e2db2016-03-03 16:20:23 +0000379 /// inside OpenMP construct.
380 const VarDecl *getThreadIDVariable() const override {
381 llvm_unreachable("No thread id for expressions");
382 }
383
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000384 /// Get the name of the capture helper.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000385 StringRef getHelperName() const override {
386 llvm_unreachable("No helper name for expressions");
387 }
388
389 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
390
391private:
392 /// Private scope to capture global variables.
393 CodeGenFunction::OMPPrivateScope PrivScope;
394};
395
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000396/// RAII for emitting code of OpenMP constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000397class InlinedOpenMPRegionRAII {
398 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000399 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
400 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000401 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000402
403public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000404 /// Constructs region for combined constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000405 /// \param CodeGen Code generation sequence for combined directives. Includes
406 /// a list of functions used for code generation of implicitly inlined
407 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000408 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000409 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000410 : CGF(CGF) {
411 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000412 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
413 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000414 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
415 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
416 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000417 BlockInfo = CGF.BlockInfo;
418 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000419 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000420
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000421 ~InlinedOpenMPRegionRAII() {
422 // Restore original CapturedStmtInfo only if we're done with code emission.
423 auto *OldCSI =
424 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
425 delete CGF.CapturedStmtInfo;
426 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000427 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
428 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000429 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000430 }
431};
432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000433/// Values for bit flags used in the ident_t to describe the fields.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000434/// All enumeric elements are named and described in accordance with the code
435/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000436enum OpenMPLocationFlags : unsigned {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Use trampoline for internal microtask.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000438 OMP_IDENT_IMD = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000439 /// Use c-style ident structure.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000440 OMP_IDENT_KMPC = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000441 /// Atomic reduction option for kmpc_reduce.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000442 OMP_ATOMIC_REDUCE = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000443 /// Explicit 'barrier' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000444 OMP_IDENT_BARRIER_EXPL = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445 /// Implicit barrier in code.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000446 OMP_IDENT_BARRIER_IMPL = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// Implicit barrier in 'for' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000448 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000449 /// Implicit barrier in 'sections' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000450 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000451 /// Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000452 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
453 /// Call of __kmp_for_static_init for static loop.
454 OMP_IDENT_WORK_LOOP = 0x200,
455 /// Call of __kmp_for_static_init for sections.
456 OMP_IDENT_WORK_SECTIONS = 0x400,
457 /// Call of __kmp_for_static_init for distribute.
458 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
459 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000460};
461
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000462/// Describes ident structure that describes a source location.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000463/// All descriptions are taken from
464/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
465/// Original structure:
466/// typedef struct ident {
467/// kmp_int32 reserved_1; /**< might be used in Fortran;
468/// see above */
469/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
470/// KMP_IDENT_KMPC identifies this union
471/// member */
472/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
473/// see above */
474///#if USE_ITT_BUILD
475/// /* but currently used for storing
476/// region-specific ITT */
477/// /* contextual information. */
478///#endif /* USE_ITT_BUILD */
479/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
480/// C++ */
481/// char const *psource; /**< String describing the source location.
482/// The string is composed of semi-colon separated
483// fields which describe the source file,
484/// the function and a pair of line numbers that
485/// delimit the construct.
486/// */
487/// } ident_t;
488enum IdentFieldIndex {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000489 /// might be used in Fortran
Alexey Bataev50b3c952016-02-19 10:38:26 +0000490 IdentField_Reserved_1,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000491 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000492 IdentField_Flags,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Not really used in Fortran any more
Alexey Bataev50b3c952016-02-19 10:38:26 +0000494 IdentField_Reserved_2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// Source[4] in Fortran, do not use for C++
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 IdentField_Reserved_3,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000497 /// String describing the source location. The string is composed of
Alexey Bataev50b3c952016-02-19 10:38:26 +0000498 /// semi-colon separated fields which describe the source file, the function
499 /// and a pair of line numbers that delimit the construct.
500 IdentField_PSource
501};
502
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000503/// Schedule types for 'omp for' loops (these enumerators are taken from
Alexey Bataev50b3c952016-02-19 10:38:26 +0000504/// the enum sched_type in kmp.h).
505enum OpenMPSchedType {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000506 /// Lower bound for default (unordered) versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000507 OMP_sch_lower = 32,
508 OMP_sch_static_chunked = 33,
509 OMP_sch_static = 34,
510 OMP_sch_dynamic_chunked = 35,
511 OMP_sch_guided_chunked = 36,
512 OMP_sch_runtime = 37,
513 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000514 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000515 OMP_sch_static_balanced_chunked = 45,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000516 /// Lower bound for 'ordered' versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000517 OMP_ord_lower = 64,
518 OMP_ord_static_chunked = 65,
519 OMP_ord_static = 66,
520 OMP_ord_dynamic_chunked = 67,
521 OMP_ord_guided_chunked = 68,
522 OMP_ord_runtime = 69,
523 OMP_ord_auto = 70,
524 OMP_sch_default = OMP_sch_static,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000525 /// dist_schedule types
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000526 OMP_dist_sch_static_chunked = 91,
527 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000528 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
529 /// Set if the monotonic schedule modifier was present.
530 OMP_sch_modifier_monotonic = (1 << 29),
531 /// Set if the nonmonotonic schedule modifier was present.
532 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000533};
534
535enum OpenMPRTLFunction {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000536 /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000537 /// kmpc_micro microtask, ...);
538 OMPRTL__kmpc_fork_call,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000539 /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000540 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
541 OMPRTL__kmpc_threadprivate_cached,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Call to void __kmpc_threadprivate_register( ident_t *,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000543 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
544 OMPRTL__kmpc_threadprivate_register,
545 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
546 OMPRTL__kmpc_global_thread_num,
547 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
548 // kmp_critical_name *crit);
549 OMPRTL__kmpc_critical,
550 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
551 // global_tid, kmp_critical_name *crit, uintptr_t hint);
552 OMPRTL__kmpc_critical_with_hint,
553 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
554 // kmp_critical_name *crit);
555 OMPRTL__kmpc_end_critical,
556 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
557 // global_tid);
558 OMPRTL__kmpc_cancel_barrier,
559 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
560 OMPRTL__kmpc_barrier,
561 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
562 OMPRTL__kmpc_for_static_fini,
563 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
564 // global_tid);
565 OMPRTL__kmpc_serialized_parallel,
566 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
567 // global_tid);
568 OMPRTL__kmpc_end_serialized_parallel,
569 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
570 // kmp_int32 num_threads);
571 OMPRTL__kmpc_push_num_threads,
572 // Call to void __kmpc_flush(ident_t *loc);
573 OMPRTL__kmpc_flush,
574 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
575 OMPRTL__kmpc_master,
576 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
577 OMPRTL__kmpc_end_master,
578 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
579 // int end_part);
580 OMPRTL__kmpc_omp_taskyield,
581 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
582 OMPRTL__kmpc_single,
583 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
584 OMPRTL__kmpc_end_single,
585 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
586 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
587 // kmp_routine_entry_t *task_entry);
588 OMPRTL__kmpc_omp_task_alloc,
589 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
590 // new_task);
591 OMPRTL__kmpc_omp_task,
592 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
593 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
594 // kmp_int32 didit);
595 OMPRTL__kmpc_copyprivate,
596 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
597 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
598 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
599 OMPRTL__kmpc_reduce,
600 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
601 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
602 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
603 // *lck);
604 OMPRTL__kmpc_reduce_nowait,
605 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
606 // kmp_critical_name *lck);
607 OMPRTL__kmpc_end_reduce,
608 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
609 // kmp_critical_name *lck);
610 OMPRTL__kmpc_end_reduce_nowait,
611 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
612 // kmp_task_t * new_task);
613 OMPRTL__kmpc_omp_task_begin_if0,
614 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
615 // kmp_task_t * new_task);
616 OMPRTL__kmpc_omp_task_complete_if0,
617 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
618 OMPRTL__kmpc_ordered,
619 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
620 OMPRTL__kmpc_end_ordered,
621 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
622 // global_tid);
623 OMPRTL__kmpc_omp_taskwait,
624 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
625 OMPRTL__kmpc_taskgroup,
626 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
627 OMPRTL__kmpc_end_taskgroup,
628 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
629 // int proc_bind);
630 OMPRTL__kmpc_push_proc_bind,
631 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
632 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
633 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
634 OMPRTL__kmpc_omp_task_with_deps,
635 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
636 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
637 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
638 OMPRTL__kmpc_omp_wait_deps,
639 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
640 // global_tid, kmp_int32 cncl_kind);
641 OMPRTL__kmpc_cancellationpoint,
642 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
643 // kmp_int32 cncl_kind);
644 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000645 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
646 // kmp_int32 num_teams, kmp_int32 thread_limit);
647 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000648 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
649 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000650 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000651 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
652 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
653 // sched, kmp_uint64 grainsize, void *task_dup);
654 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000655 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
656 // num_dims, struct kmp_dim *dims);
657 OMPRTL__kmpc_doacross_init,
658 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
659 OMPRTL__kmpc_doacross_fini,
660 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
661 // *vec);
662 OMPRTL__kmpc_doacross_post,
663 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
664 // *vec);
665 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000666 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
667 // *data);
668 OMPRTL__kmpc_task_reduction_init,
669 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
670 // *d);
671 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000672
673 //
674 // Offloading related calls
675 //
George Rokos63bc9d62017-11-21 18:25:12 +0000676 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
677 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000678 // *arg_types);
679 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000680 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
681 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
682 // *arg_types);
683 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000684 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
685 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
686 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000687 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000688 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
689 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
690 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
691 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000692 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
693 OMPRTL__tgt_register_lib,
694 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
695 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000696 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
697 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000698 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000699 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
700 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
701 // *arg_types);
702 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000703 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
704 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000705 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000706 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
707 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
708 // *arg_types);
709 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000710 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
711 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000712 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000713 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
714 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
715 // *arg_types);
716 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000717};
718
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000719/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
720/// region.
721class CleanupTy final : public EHScopeStack::Cleanup {
722 PrePostActionTy *Action;
723
724public:
725 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
726 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
727 if (!CGF.HaveInsertPoint())
728 return;
729 Action->Exit(CGF);
730 }
731};
732
Hans Wennborg7eb54642015-09-10 17:07:54 +0000733} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000734
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000735void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
736 CodeGenFunction::RunCleanupsScope Scope(CGF);
737 if (PrePostAction) {
738 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
739 Callback(CodeGen, CGF, *PrePostAction);
740 } else {
741 PrePostActionTy Action;
742 Callback(CodeGen, CGF, Action);
743 }
744}
745
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000746/// Check if the combiner is a call to UDR combiner and if it is so return the
747/// UDR decl used for reduction.
748static const OMPDeclareReductionDecl *
749getReductionInit(const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000750 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
751 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
752 if (const auto *DRE =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000753 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000754 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000755 return DRD;
756 return nullptr;
757}
758
759static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
760 const OMPDeclareReductionDecl *DRD,
761 const Expr *InitOp,
762 Address Private, Address Original,
763 QualType Ty) {
764 if (DRD->getInitializer()) {
765 std::pair<llvm::Function *, llvm::Function *> Reduction =
766 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000767 const auto *CE = cast<CallExpr>(InitOp);
768 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000769 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
770 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000771 const auto *LHSDRE =
772 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
773 const auto *RHSDRE =
774 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000775 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
776 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000777 [=]() { return Private; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000778 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000779 [=]() { return Original; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000780 (void)PrivateScope.Privatize();
781 RValue Func = RValue::get(Reduction.second);
782 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
783 CGF.EmitIgnoredExpr(InitOp);
784 } else {
785 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
Alexey Bataev18fa2322018-05-02 14:20:50 +0000786 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000787 auto *GV = new llvm::GlobalVariable(
788 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
Alexey Bataev18fa2322018-05-02 14:20:50 +0000789 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000790 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
791 RValue InitRVal;
792 switch (CGF.getEvaluationKind(Ty)) {
793 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000794 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000795 break;
796 case TEK_Complex:
797 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000798 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000799 break;
800 case TEK_Aggregate:
801 InitRVal = RValue::getAggregate(LV.getAddress());
802 break;
803 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000804 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000805 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
806 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
807 /*IsInitializer=*/false);
808 }
809}
810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811/// Emit initialization of arrays of complex types.
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000812/// \param DestAddr Address of the array.
813/// \param Type Type of array.
814/// \param Init Initial expression of array.
815/// \param SrcAddr Address of the original array.
816static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000817 QualType Type, bool EmitDeclareReductionInit,
818 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000819 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000820 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000821 // Perform element-by-element initialization.
822 QualType ElementTy;
823
824 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000825 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
826 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000827 DestAddr =
828 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
829 if (DRD)
830 SrcAddr =
831 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
832
833 llvm::Value *SrcBegin = nullptr;
834 if (DRD)
835 SrcBegin = SrcAddr.getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000836 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000837 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000838 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000839 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000840 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
841 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
842 llvm::Value *IsEmpty =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000843 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
844 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
845
846 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000847 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000848 CGF.EmitBlock(BodyBB);
849
850 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
851
852 llvm::PHINode *SrcElementPHI = nullptr;
853 Address SrcElementCurrent = Address::invalid();
854 if (DRD) {
855 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
856 "omp.arraycpy.srcElementPast");
857 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
858 SrcElementCurrent =
859 Address(SrcElementPHI,
860 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
861 }
862 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
863 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
864 DestElementPHI->addIncoming(DestBegin, EntryBB);
865 Address DestElementCurrent =
866 Address(DestElementPHI,
867 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
868
869 // Emit copy.
870 {
871 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000872 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000873 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
874 SrcElementCurrent, ElementTy);
875 } else
876 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
877 /*IsInitializer=*/false);
878 }
879
880 if (DRD) {
881 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000882 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000883 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
884 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
885 }
886
887 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000888 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000889 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
890 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000891 llvm::Value *Done =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000892 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
893 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
894 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
895
896 // Done.
897 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
898}
899
Alexey Bataev92327c52018-03-26 16:40:55 +0000900static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
901isDeclareTargetDeclaration(const ValueDecl *VD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000902 for (const Decl *D : VD->redecls()) {
Alexey Bataev92327c52018-03-26 16:40:55 +0000903 if (!D->hasAttrs())
904 continue;
905 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
906 return Attr->getMapType();
907 }
Alexey Bataevfb388282018-05-01 14:09:46 +0000908 if (const auto *V = dyn_cast<VarDecl>(VD)) {
909 if (const VarDecl *TD = V->getTemplateInstantiationPattern())
910 return isDeclareTargetDeclaration(TD);
911 } else if (const auto *FD = dyn_cast<FunctionDecl>(VD)) {
912 if (const auto *TD = FD->getTemplateInstantiationPattern())
913 return isDeclareTargetDeclaration(TD);
914 }
915
Alexey Bataev92327c52018-03-26 16:40:55 +0000916 return llvm::None;
917}
918
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000919LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000920 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000921}
922
923LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
924 const Expr *E) {
925 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
926 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
927 return LValue();
928}
929
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000930void ReductionCodeGen::emitAggregateInitialization(
931 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
932 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000933 // Emit VarDecl with copy init for arrays.
934 // Get the address of the original variable captured in current
935 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000936 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000937 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000938 bool EmitDeclareReductionInit =
939 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000941 EmitDeclareReductionInit,
942 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
943 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000944 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000945}
946
947ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
948 ArrayRef<const Expr *> Privates,
949 ArrayRef<const Expr *> ReductionOps) {
950 ClausesData.reserve(Shareds.size());
951 SharedAddresses.reserve(Shareds.size());
952 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000953 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 auto IPriv = Privates.begin();
955 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000956 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000957 ClausesData.emplace_back(Ref, *IPriv, *IRed);
958 std::advance(IPriv, 1);
959 std::advance(IRed, 1);
960 }
961}
962
963void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
964 assert(SharedAddresses.size() == N &&
965 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000966 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
967 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
968 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000969}
970
971void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000972 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000973 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
974 QualType PrivateType = PrivateVD->getType();
975 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000976 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000977 Sizes.emplace_back(
978 CGF.getTypeSize(
979 SharedAddresses[N].first.getType().getNonReferenceType()),
980 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000981 return;
982 }
983 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000984 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000985 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000986 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
987 ->getElementType();
988 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000989 if (AsArraySection) {
990 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
991 SharedAddresses[N].first.getPointer());
992 Size = CGF.Builder.CreateNUWAdd(
993 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000994 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000995 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000996 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000997 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000998 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000999 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001000 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001001 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1002 CGF,
1003 cast<OpaqueValueExpr>(
1004 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1005 RValue::get(Size));
1006 CGF.EmitVariablyModifiedType(PrivateType);
1007}
1008
1009void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
1010 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001011 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001012 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1013 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001014 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001015 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001016 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001017 "items.");
1018 return;
1019 }
1020 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1021 CGF,
1022 cast<OpaqueValueExpr>(
1023 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1024 RValue::get(Size));
1025 CGF.EmitVariablyModifiedType(PrivateType);
1026}
1027
1028void ReductionCodeGen::emitInitialization(
1029 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1030 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1031 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001032 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001033 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001034 const OMPDeclareReductionDecl *DRD =
1035 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001036 QualType PrivateType = PrivateVD->getType();
1037 PrivateAddr = CGF.Builder.CreateElementBitCast(
1038 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1039 QualType SharedType = SharedAddresses[N].first.getType();
1040 SharedLVal = CGF.MakeAddrLValue(
1041 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1042 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001043 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001044 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001045 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001046 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001047 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1048 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1049 PrivateAddr, SharedLVal.getAddress(),
1050 SharedLVal.getType());
1051 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1052 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1053 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1054 PrivateVD->getType().getQualifiers(),
1055 /*IsInitializer=*/false);
1056 }
1057}
1058
1059bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001060 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001061 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1062 QualType PrivateType = PrivateVD->getType();
1063 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1064 return DTorKind != QualType::DK_none;
1065}
1066
1067void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1068 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001069 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001070 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1071 QualType PrivateType = PrivateVD->getType();
1072 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1073 if (needCleanups(N)) {
1074 PrivateAddr = CGF.Builder.CreateElementBitCast(
1075 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1076 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1077 }
1078}
1079
1080static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1081 LValue BaseLV) {
1082 BaseTy = BaseTy.getNonReferenceType();
1083 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1084 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001085 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001086 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001087 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001088 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1089 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001090 }
1091 BaseTy = BaseTy->getPointeeType();
1092 }
1093 return CGF.MakeAddrLValue(
1094 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1095 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001096 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001097 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001098}
1099
1100static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1101 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1102 llvm::Value *Addr) {
1103 Address Tmp = Address::invalid();
1104 Address TopTmp = Address::invalid();
1105 Address MostTopTmp = Address::invalid();
1106 BaseTy = BaseTy.getNonReferenceType();
1107 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1108 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1109 Tmp = CGF.CreateMemTemp(BaseTy);
1110 if (TopTmp.isValid())
1111 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1112 else
1113 MostTopTmp = Tmp;
1114 TopTmp = Tmp;
1115 BaseTy = BaseTy->getPointeeType();
1116 }
1117 llvm::Type *Ty = BaseLVType;
1118 if (Tmp.isValid())
1119 Ty = Tmp.getElementType();
1120 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1121 if (Tmp.isValid()) {
1122 CGF.Builder.CreateStore(Addr, Tmp);
1123 return MostTopTmp;
1124 }
1125 return Address(Addr, BaseLVAlignment);
1126}
1127
Alexey Bataev1c44e152018-03-06 18:59:43 +00001128static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001129 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001130 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1131 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1132 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001133 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001134 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 Base = TempASE->getBase()->IgnoreParenImpCasts();
1136 DE = cast<DeclRefExpr>(Base);
1137 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001138 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1139 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1140 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001141 Base = TempASE->getBase()->IgnoreParenImpCasts();
1142 DE = cast<DeclRefExpr>(Base);
1143 OrigVD = cast<VarDecl>(DE->getDecl());
1144 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001145 return OrigVD;
1146}
1147
1148Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1149 Address PrivateAddr) {
1150 const DeclRefExpr *DE;
1151 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001152 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001153 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001154 LValue BaseLValue =
1155 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1156 OriginalBaseLValue);
1157 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1158 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001159 llvm::Value *PrivatePointer =
1160 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1161 PrivateAddr.getPointer(),
1162 SharedAddresses[N].first.getAddress().getType());
1163 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001164 return castToBase(CGF, OrigVD->getType(),
1165 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001166 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001167 OriginalBaseLValue.getAlignment(), Ptr);
1168 }
1169 BaseDecls.emplace_back(
1170 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1171 return PrivateAddr;
1172}
1173
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001174bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001175 const OMPDeclareReductionDecl *DRD =
1176 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001177 return DRD && DRD->getInitializer();
1178}
1179
Alexey Bataev18095712014-10-10 12:19:54 +00001180LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001181 return CGF.EmitLoadOfPointerLValue(
1182 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1183 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001184}
1185
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001186void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001187 if (!CGF.HaveInsertPoint())
1188 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001189 // 1.2.2 OpenMP Language Terminology
1190 // Structured block - An executable statement with a single entry at the
1191 // top and a single exit at the bottom.
1192 // The point of exit cannot be a branch out of the structured block.
1193 // longjmp() and throw() must not violate the entry/exit criteria.
1194 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001195 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001196 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001197}
1198
Alexey Bataev62b63b12015-03-10 07:28:44 +00001199LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1200 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001201 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1202 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001203 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001204}
1205
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001206static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1207 QualType FieldTy) {
1208 auto *Field = FieldDecl::Create(
1209 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1210 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1211 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1212 Field->setAccess(AS_public);
1213 DC->addDecl(Field);
1214 return Field;
1215}
1216
Alexey Bataev18fa2322018-05-02 14:20:50 +00001217CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1218 StringRef Separator)
1219 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1220 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001221 ASTContext &C = CGM.getContext();
1222 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1223 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1224 RD->startDefinition();
1225 // reserved_1
1226 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1227 // flags
1228 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1229 // reserved_2
1230 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1231 // reserved_3
1232 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1233 // psource
1234 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1235 RD->completeDefinition();
1236 IdentQTy = C.getRecordType(RD);
1237 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001238 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001239
1240 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001241}
1242
Alexey Bataev91797552015-03-18 04:13:55 +00001243void CGOpenMPRuntime::clear() {
1244 InternalVars.clear();
1245}
1246
Alexey Bataev18fa2322018-05-02 14:20:50 +00001247std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1248 SmallString<128> Buffer;
1249 llvm::raw_svector_ostream OS(Buffer);
1250 StringRef Sep = FirstSeparator;
1251 for (StringRef Part : Parts) {
1252 OS << Sep << Part;
1253 Sep = Separator;
1254 }
1255 return OS.str();
1256}
1257
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001258static llvm::Function *
1259emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1260 const Expr *CombinerInitializer, const VarDecl *In,
1261 const VarDecl *Out, bool IsCombiner) {
1262 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001263 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001264 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1265 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001266 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001267 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001268 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001269 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001270 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001271 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001272 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001273 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001274 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001275 std::string Name = CGM.getOpenMPRuntime().getName(
1276 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1277 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1278 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001279 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001280 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001281 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001282 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001283 CodeGenFunction CGF(CGM);
1284 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1285 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001286 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1287 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001288 CodeGenFunction::OMPPrivateScope Scope(CGF);
1289 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001290 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001291 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1292 .getAddress();
1293 });
1294 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001295 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001296 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1297 .getAddress();
1298 });
1299 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001300 if (!IsCombiner && Out->hasInit() &&
1301 !CGF.isTrivialInitializer(Out->getInit())) {
1302 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1303 Out->getType().getQualifiers(),
1304 /*IsInitializer=*/true);
1305 }
1306 if (CombinerInitializer)
1307 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001308 Scope.ForceCleanup();
1309 CGF.FinishFunction();
1310 return Fn;
1311}
1312
1313void CGOpenMPRuntime::emitUserDefinedReduction(
1314 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1315 if (UDRMap.count(D) > 0)
1316 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001317 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001318 if (!In || !Out) {
1319 In = &C.Idents.get("omp_in");
1320 Out = &C.Idents.get("omp_out");
1321 }
1322 llvm::Function *Combiner = emitCombinerOrInitializer(
1323 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1324 cast<VarDecl>(D->lookup(Out).front()),
1325 /*IsCombiner=*/true);
1326 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001327 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001328 if (!Priv || !Orig) {
1329 Priv = &C.Idents.get("omp_priv");
1330 Orig = &C.Idents.get("omp_orig");
1331 }
1332 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001333 CGM, D->getType(),
1334 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1335 : nullptr,
1336 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001337 cast<VarDecl>(D->lookup(Priv).front()),
1338 /*IsCombiner=*/false);
1339 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001340 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001341 if (CGF) {
1342 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1343 Decls.second.push_back(D);
1344 }
1345}
1346
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001347std::pair<llvm::Function *, llvm::Function *>
1348CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1349 auto I = UDRMap.find(D);
1350 if (I != UDRMap.end())
1351 return I->second;
1352 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1353 return UDRMap.lookup(D);
1354}
1355
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001356static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1357 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1358 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1359 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001360 assert(ThreadIDVar->getType()->isPointerType() &&
1361 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001362 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001363 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001364 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001365 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001366 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001367 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001368 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001369 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001370 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001371 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001372 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001373 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001374 else if (const auto *OPFD =
1375 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001376 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001377 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001378 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1379 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001380 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001381 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001382 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001383 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001384}
1385
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001386llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1387 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1388 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1389 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1390 return emitParallelOrTeamsOutlinedFunction(
1391 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1392}
1393
1394llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1395 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1396 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1397 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1398 return emitParallelOrTeamsOutlinedFunction(
1399 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1400}
1401
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001402llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1403 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001404 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1405 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1406 bool Tied, unsigned &NumberOfParts) {
1407 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1408 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001409 llvm::Value *ThreadID = getThreadID(CGF, D.getLocStart());
1410 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001411 llvm::Value *TaskArgs[] = {
1412 UpLoc, ThreadID,
1413 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1414 TaskTVar->getType()->castAs<PointerType>())
1415 .getPointer()};
1416 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1417 };
1418 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1419 UntiedCodeGen);
1420 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001421 assert(!ThreadIDVar->getType()->isPointerType() &&
1422 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001423 const OpenMPDirectiveKind Region =
1424 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1425 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001426 const CapturedStmt *CS = D.getCapturedStmt(Region);
1427 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001428 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001429 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1430 InnermostKind,
1431 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001432 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001433 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001434 if (!Tied)
1435 NumberOfParts = Action.getNumberOfParts();
1436 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001437}
1438
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001439static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1440 const RecordDecl *RD, const CGRecordLayout &RL,
1441 ArrayRef<llvm::Constant *> Data) {
1442 llvm::StructType *StructTy = RL.getLLVMType();
1443 unsigned PrevIdx = 0;
1444 ConstantInitBuilder CIBuilder(CGM);
1445 auto DI = Data.begin();
1446 for (const FieldDecl *FD : RD->fields()) {
1447 unsigned Idx = RL.getLLVMFieldNo(FD);
1448 // Fill the alignment.
1449 for (unsigned I = PrevIdx; I < Idx; ++I)
1450 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1451 PrevIdx = Idx + 1;
1452 Fields.add(*DI);
1453 ++DI;
1454 }
1455}
1456
1457template <class... As>
1458static llvm::GlobalVariable *
1459createConstantGlobalStruct(CodeGenModule &CGM, QualType Ty,
1460 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1461 As &&... Args) {
1462 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1463 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1464 ConstantInitBuilder CIBuilder(CGM);
1465 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1466 buildStructValue(Fields, CGM, RD, RL, Data);
1467 return Fields.finishAndCreateGlobal(
1468 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty),
1469 /*isConstant=*/true, std::forward<As>(Args)...);
1470}
1471
1472template <typename T>
1473void createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1474 ArrayRef<llvm::Constant *> Data,
1475 T &Parent) {
1476 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1477 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1478 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1479 buildStructValue(Fields, CGM, RD, RL, Data);
1480 Fields.finishAndAddTo(Parent);
1481}
1482
Alexey Bataev50b3c952016-02-19 10:38:26 +00001483Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001484 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001485 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001486 if (!Entry) {
1487 if (!DefaultOpenMPPSource) {
1488 // Initialize default location for psource field of ident_t structure of
1489 // all ident_t objects. Format is ";file;function;line;column;;".
1490 // Taken from
1491 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1492 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001493 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001494 DefaultOpenMPPSource =
1495 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1496 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001497
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001498 llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1499 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1500 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1501 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1502 DefaultOpenMPPSource};
1503 llvm::GlobalValue *DefaultOpenMPLocation = createConstantGlobalStruct(
1504 CGM, IdentQTy, Data, "", llvm::GlobalValue::PrivateLinkage);
1505 DefaultOpenMPLocation->setUnnamedAddr(
1506 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001507
John McCall7f416cc2015-09-08 08:05:57 +00001508 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001509 }
John McCall7f416cc2015-09-08 08:05:57 +00001510 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001511}
1512
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001513llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1514 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001515 unsigned Flags) {
1516 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001517 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001518 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001519 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001520 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001521
1522 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1523
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001524 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001525 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001526 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1527 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001528 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001529
Alexander Musmanc6388682014-12-15 07:07:06 +00001530 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1531 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001532 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001533 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001534 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001535 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001536 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001537 LocValue = AI;
1538
1539 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1540 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001541 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001542 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001543 }
1544
1545 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001546 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1547 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1548 LValue PSource =
1549 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001550
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001551 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001552 if (OMPDebugLoc == nullptr) {
1553 SmallString<128> Buffer2;
1554 llvm::raw_svector_ostream OS2(Buffer2);
1555 // Build debug location
1556 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1557 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001558 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001559 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001560 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1561 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1562 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001563 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001564 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001565 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001566
John McCall7f416cc2015-09-08 08:05:57 +00001567 // Our callers always pass this to a runtime function, so for
1568 // convenience, go ahead and return a naked pointer.
1569 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001570}
1571
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001572llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1573 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001574 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1575
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001576 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001577 // Check whether we've already cached a load of the thread id in this
1578 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001579 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001580 if (I != OpenMPLocThreadIDMap.end()) {
1581 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001582 if (ThreadID != nullptr)
1583 return ThreadID;
1584 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001585 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001586 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1587 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001588 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001589 if (auto *OMPRegionInfo =
1590 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1591 if (OMPRegionInfo->getThreadIDVariable()) {
1592 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001593 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001594 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001595 // If value loaded in entry block, cache it and use it everywhere in
1596 // function.
1597 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1598 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1599 Elem.second.ThreadID = ThreadID;
1600 }
1601 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001602 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001603 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001604 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001605
1606 // This is not an outlined function region - need to call __kmpc_int32
1607 // kmpc_global_thread_num(ident_t *loc).
1608 // Generate thread id value and cache this value for use across the
1609 // function.
1610 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1611 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001612 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001613 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1614 emitUpdateLocation(CGF, Loc));
1615 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001616 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001617 Elem.second.ThreadID = Call;
1618 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001619}
1620
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001621void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001622 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001623 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1624 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001625 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001626 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001627 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001628 FunctionUDRMap.erase(CGF.CurFn);
1629 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001630}
1631
1632llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001633 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001634}
1635
1636llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001637 if (!Kmpc_MicroTy) {
1638 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1639 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1640 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1641 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1642 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001643 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1644}
1645
1646llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001647CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001648 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001649 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001650 case OMPRTL__kmpc_fork_call: {
1651 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1652 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001653 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1654 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001655 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001656 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001657 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1658 break;
1659 }
1660 case OMPRTL__kmpc_global_thread_num: {
1661 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001662 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001663 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001664 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001665 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1666 break;
1667 }
Alexey Bataev97720002014-11-11 04:05:39 +00001668 case OMPRTL__kmpc_threadprivate_cached: {
1669 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1670 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1671 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1672 CGM.VoidPtrTy, CGM.SizeTy,
1673 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001674 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001675 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1676 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1677 break;
1678 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001679 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001680 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1681 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001682 llvm::Type *TypeParams[] = {
1683 getIdentTyPointerTy(), CGM.Int32Ty,
1684 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001685 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001686 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1687 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1688 break;
1689 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001690 case OMPRTL__kmpc_critical_with_hint: {
1691 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1692 // kmp_critical_name *crit, uintptr_t hint);
1693 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1694 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1695 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001696 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001697 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1698 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1699 break;
1700 }
Alexey Bataev97720002014-11-11 04:05:39 +00001701 case OMPRTL__kmpc_threadprivate_register: {
1702 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1703 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1704 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001705 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001706 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1707 /*isVarArg*/ false)->getPointerTo();
1708 // typedef void *(*kmpc_cctor)(void *, void *);
1709 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001710 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001711 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001712 /*isVarArg*/ false)
1713 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001714 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001715 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001716 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1717 ->getPointerTo();
1718 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1719 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001720 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001721 /*isVarArg*/ false);
1722 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1723 break;
1724 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001725 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001726 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1727 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001728 llvm::Type *TypeParams[] = {
1729 getIdentTyPointerTy(), CGM.Int32Ty,
1730 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001731 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001732 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1733 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1734 break;
1735 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001736 case OMPRTL__kmpc_cancel_barrier: {
1737 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1738 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001739 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001740 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001741 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1742 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001743 break;
1744 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001745 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001746 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001747 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001748 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001749 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1750 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1751 break;
1752 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001753 case OMPRTL__kmpc_for_static_fini: {
1754 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1755 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001756 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001757 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1758 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1759 break;
1760 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001761 case OMPRTL__kmpc_push_num_threads: {
1762 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1763 // kmp_int32 num_threads)
1764 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1765 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001766 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001767 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1768 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1769 break;
1770 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001771 case OMPRTL__kmpc_serialized_parallel: {
1772 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1773 // global_tid);
1774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001775 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001776 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1778 break;
1779 }
1780 case OMPRTL__kmpc_end_serialized_parallel: {
1781 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1782 // global_tid);
1783 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001784 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001785 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1786 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1787 break;
1788 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001789 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001790 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001791 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001792 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001794 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1795 break;
1796 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001797 case OMPRTL__kmpc_master: {
1798 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001800 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001801 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1802 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1803 break;
1804 }
1805 case OMPRTL__kmpc_end_master: {
1806 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1807 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001808 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001809 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1810 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1811 break;
1812 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001813 case OMPRTL__kmpc_omp_taskyield: {
1814 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1815 // int end_part);
1816 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001817 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001818 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1819 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1820 break;
1821 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001822 case OMPRTL__kmpc_single: {
1823 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1824 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001825 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001826 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1827 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1828 break;
1829 }
1830 case OMPRTL__kmpc_end_single: {
1831 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1832 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001833 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001834 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1835 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1836 break;
1837 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001838 case OMPRTL__kmpc_omp_task_alloc: {
1839 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1840 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1841 // kmp_routine_entry_t *task_entry);
1842 assert(KmpRoutineEntryPtrTy != nullptr &&
1843 "Type kmp_routine_entry_t must be created.");
1844 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1845 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1846 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001847 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001848 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1849 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1850 break;
1851 }
1852 case OMPRTL__kmpc_omp_task: {
1853 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1854 // *new_task);
1855 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1856 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001857 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001858 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1859 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1860 break;
1861 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001862 case OMPRTL__kmpc_copyprivate: {
1863 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001864 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001865 // kmp_int32 didit);
1866 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1867 auto *CpyFnTy =
1868 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001869 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001870 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1871 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001872 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001873 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1874 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1875 break;
1876 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001877 case OMPRTL__kmpc_reduce: {
1878 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1879 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1880 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1881 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1882 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1883 /*isVarArg=*/false);
1884 llvm::Type *TypeParams[] = {
1885 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1886 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1887 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001888 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001889 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1890 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1891 break;
1892 }
1893 case OMPRTL__kmpc_reduce_nowait: {
1894 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1895 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1896 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1897 // *lck);
1898 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1899 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1900 /*isVarArg=*/false);
1901 llvm::Type *TypeParams[] = {
1902 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1903 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1904 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001905 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001906 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1907 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1908 break;
1909 }
1910 case OMPRTL__kmpc_end_reduce: {
1911 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1912 // kmp_critical_name *lck);
1913 llvm::Type *TypeParams[] = {
1914 getIdentTyPointerTy(), CGM.Int32Ty,
1915 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001916 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001917 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1918 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1919 break;
1920 }
1921 case OMPRTL__kmpc_end_reduce_nowait: {
1922 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1923 // kmp_critical_name *lck);
1924 llvm::Type *TypeParams[] = {
1925 getIdentTyPointerTy(), CGM.Int32Ty,
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.VoidTy, TypeParams, /*isVarArg=*/false);
1929 RTLFn =
1930 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1931 break;
1932 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001933 case OMPRTL__kmpc_omp_task_begin_if0: {
1934 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1935 // *new_task);
1936 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1937 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001938 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001939 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1940 RTLFn =
1941 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1942 break;
1943 }
1944 case OMPRTL__kmpc_omp_task_complete_if0: {
1945 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1946 // *new_task);
1947 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1948 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001949 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001950 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1952 /*Name=*/"__kmpc_omp_task_complete_if0");
1953 break;
1954 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001955 case OMPRTL__kmpc_ordered: {
1956 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1957 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001958 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001959 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1960 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1961 break;
1962 }
1963 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001964 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001965 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001966 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001967 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1968 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1969 break;
1970 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001971 case OMPRTL__kmpc_omp_taskwait: {
1972 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1973 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001974 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001975 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1976 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1977 break;
1978 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001979 case OMPRTL__kmpc_taskgroup: {
1980 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1981 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001982 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001983 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1984 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1985 break;
1986 }
1987 case OMPRTL__kmpc_end_taskgroup: {
1988 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1989 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001990 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001991 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1992 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1993 break;
1994 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001995 case OMPRTL__kmpc_push_proc_bind: {
1996 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1997 // int proc_bind)
1998 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001999 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002000 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2001 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2002 break;
2003 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002004 case OMPRTL__kmpc_omp_task_with_deps: {
2005 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2006 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2007 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2008 llvm::Type *TypeParams[] = {
2009 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2010 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002011 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002012 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2013 RTLFn =
2014 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2015 break;
2016 }
2017 case OMPRTL__kmpc_omp_wait_deps: {
2018 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2019 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2020 // kmp_depend_info_t *noalias_dep_list);
2021 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2022 CGM.Int32Ty, CGM.VoidPtrTy,
2023 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002024 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002025 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2026 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2027 break;
2028 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002029 case OMPRTL__kmpc_cancellationpoint: {
2030 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2031 // global_tid, kmp_int32 cncl_kind)
2032 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002033 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002034 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2035 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2036 break;
2037 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002038 case OMPRTL__kmpc_cancel: {
2039 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2040 // kmp_int32 cncl_kind)
2041 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002042 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002043 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2044 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2045 break;
2046 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002047 case OMPRTL__kmpc_push_num_teams: {
2048 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2049 // kmp_int32 num_teams, kmp_int32 num_threads)
2050 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2051 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002052 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002053 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2054 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2055 break;
2056 }
2057 case OMPRTL__kmpc_fork_teams: {
2058 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2059 // microtask, ...);
2060 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2061 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002062 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002063 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2064 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2065 break;
2066 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002067 case OMPRTL__kmpc_taskloop: {
2068 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2069 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2070 // sched, kmp_uint64 grainsize, void *task_dup);
2071 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2072 CGM.IntTy,
2073 CGM.VoidPtrTy,
2074 CGM.IntTy,
2075 CGM.Int64Ty->getPointerTo(),
2076 CGM.Int64Ty->getPointerTo(),
2077 CGM.Int64Ty,
2078 CGM.IntTy,
2079 CGM.IntTy,
2080 CGM.Int64Ty,
2081 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002082 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002083 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2084 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2085 break;
2086 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002087 case OMPRTL__kmpc_doacross_init: {
2088 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2089 // num_dims, struct kmp_dim *dims);
2090 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2091 CGM.Int32Ty,
2092 CGM.Int32Ty,
2093 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002094 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002095 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2096 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2097 break;
2098 }
2099 case OMPRTL__kmpc_doacross_fini: {
2100 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2101 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002102 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002103 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2104 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2105 break;
2106 }
2107 case OMPRTL__kmpc_doacross_post: {
2108 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2109 // *vec);
2110 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2111 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002112 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002113 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2114 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2115 break;
2116 }
2117 case OMPRTL__kmpc_doacross_wait: {
2118 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2119 // *vec);
2120 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2121 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002122 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002123 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2124 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2125 break;
2126 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002127 case OMPRTL__kmpc_task_reduction_init: {
2128 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2129 // *data);
2130 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002131 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002132 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2133 RTLFn =
2134 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2135 break;
2136 }
2137 case OMPRTL__kmpc_task_reduction_get_th_data: {
2138 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2139 // *d);
2140 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002141 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002142 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2143 RTLFn = CGM.CreateRuntimeFunction(
2144 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2145 break;
2146 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002147 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002148 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2149 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002150 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002151 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002152 CGM.VoidPtrTy,
2153 CGM.Int32Ty,
2154 CGM.VoidPtrPtrTy,
2155 CGM.VoidPtrPtrTy,
2156 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002157 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002158 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002159 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2160 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2161 break;
2162 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002163 case OMPRTL__tgt_target_nowait: {
2164 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2165 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2166 // int64_t *arg_types);
2167 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2168 CGM.VoidPtrTy,
2169 CGM.Int32Ty,
2170 CGM.VoidPtrPtrTy,
2171 CGM.VoidPtrPtrTy,
2172 CGM.SizeTy->getPointerTo(),
2173 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002174 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002175 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2176 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2177 break;
2178 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002179 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002180 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002181 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002182 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2183 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002184 CGM.VoidPtrTy,
2185 CGM.Int32Ty,
2186 CGM.VoidPtrPtrTy,
2187 CGM.VoidPtrPtrTy,
2188 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002189 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002190 CGM.Int32Ty,
2191 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002192 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002193 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2194 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2195 break;
2196 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002197 case OMPRTL__tgt_target_teams_nowait: {
2198 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2199 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2200 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2201 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2202 CGM.VoidPtrTy,
2203 CGM.Int32Ty,
2204 CGM.VoidPtrPtrTy,
2205 CGM.VoidPtrPtrTy,
2206 CGM.SizeTy->getPointerTo(),
2207 CGM.Int64Ty->getPointerTo(),
2208 CGM.Int32Ty,
2209 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002210 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002211 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2212 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2213 break;
2214 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002215 case OMPRTL__tgt_register_lib: {
2216 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2217 QualType ParamTy =
2218 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2219 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002220 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002221 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2222 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2223 break;
2224 }
2225 case OMPRTL__tgt_unregister_lib: {
2226 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2227 QualType ParamTy =
2228 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2229 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002230 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002231 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2232 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2233 break;
2234 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002235 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002236 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2237 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2238 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002239 CGM.Int32Ty,
2240 CGM.VoidPtrPtrTy,
2241 CGM.VoidPtrPtrTy,
2242 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002243 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002244 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002245 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2246 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2247 break;
2248 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002249 case OMPRTL__tgt_target_data_begin_nowait: {
2250 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2251 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2252 // *arg_types);
2253 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2254 CGM.Int32Ty,
2255 CGM.VoidPtrPtrTy,
2256 CGM.VoidPtrPtrTy,
2257 CGM.SizeTy->getPointerTo(),
2258 CGM.Int64Ty->getPointerTo()};
2259 auto *FnTy =
2260 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2261 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2262 break;
2263 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002264 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002265 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2266 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2267 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002268 CGM.Int32Ty,
2269 CGM.VoidPtrPtrTy,
2270 CGM.VoidPtrPtrTy,
2271 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002272 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002273 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002274 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2275 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2276 break;
2277 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002278 case OMPRTL__tgt_target_data_end_nowait: {
2279 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2280 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2281 // *arg_types);
2282 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2283 CGM.Int32Ty,
2284 CGM.VoidPtrPtrTy,
2285 CGM.VoidPtrPtrTy,
2286 CGM.SizeTy->getPointerTo(),
2287 CGM.Int64Ty->getPointerTo()};
2288 auto *FnTy =
2289 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2290 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2291 break;
2292 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002293 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002294 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2295 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2296 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002297 CGM.Int32Ty,
2298 CGM.VoidPtrPtrTy,
2299 CGM.VoidPtrPtrTy,
2300 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002301 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002302 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002303 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2304 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2305 break;
2306 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002307 case OMPRTL__tgt_target_data_update_nowait: {
2308 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2309 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2310 // *arg_types);
2311 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2312 CGM.Int32Ty,
2313 CGM.VoidPtrPtrTy,
2314 CGM.VoidPtrPtrTy,
2315 CGM.SizeTy->getPointerTo(),
2316 CGM.Int64Ty->getPointerTo()};
2317 auto *FnTy =
2318 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2319 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2320 break;
2321 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002322 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002323 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002324 return RTLFn;
2325}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002326
Alexander Musman21212e42015-03-13 10:38:23 +00002327llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2328 bool IVSigned) {
2329 assert((IVSize == 32 || IVSize == 64) &&
2330 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002331 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2332 : "__kmpc_for_static_init_4u")
2333 : (IVSigned ? "__kmpc_for_static_init_8"
2334 : "__kmpc_for_static_init_8u");
2335 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2336 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002337 llvm::Type *TypeParams[] = {
2338 getIdentTyPointerTy(), // loc
2339 CGM.Int32Ty, // tid
2340 CGM.Int32Ty, // schedtype
2341 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2342 PtrTy, // p_lower
2343 PtrTy, // p_upper
2344 PtrTy, // p_stride
2345 ITy, // incr
2346 ITy // chunk
2347 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002348 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002349 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2350 return CGM.CreateRuntimeFunction(FnTy, Name);
2351}
2352
Alexander Musman92bdaab2015-03-12 13:37:50 +00002353llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2354 bool IVSigned) {
2355 assert((IVSize == 32 || IVSize == 64) &&
2356 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002357 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002358 IVSize == 32
2359 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2360 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002361 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002362 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2363 CGM.Int32Ty, // tid
2364 CGM.Int32Ty, // schedtype
2365 ITy, // lower
2366 ITy, // upper
2367 ITy, // stride
2368 ITy // chunk
2369 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002370 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002371 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2372 return CGM.CreateRuntimeFunction(FnTy, Name);
2373}
2374
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002375llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2376 bool IVSigned) {
2377 assert((IVSize == 32 || IVSize == 64) &&
2378 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002379 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002380 IVSize == 32
2381 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2382 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2383 llvm::Type *TypeParams[] = {
2384 getIdentTyPointerTy(), // loc
2385 CGM.Int32Ty, // tid
2386 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002387 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002388 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2389 return CGM.CreateRuntimeFunction(FnTy, Name);
2390}
2391
Alexander Musman92bdaab2015-03-12 13:37:50 +00002392llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2393 bool IVSigned) {
2394 assert((IVSize == 32 || IVSize == 64) &&
2395 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002396 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002397 IVSize == 32
2398 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2399 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002400 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2401 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002402 llvm::Type *TypeParams[] = {
2403 getIdentTyPointerTy(), // loc
2404 CGM.Int32Ty, // tid
2405 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2406 PtrTy, // p_lower
2407 PtrTy, // p_upper
2408 PtrTy // p_stride
2409 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002410 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002411 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2412 return CGM.CreateRuntimeFunction(FnTy, Name);
2413}
2414
Alexey Bataev03f270c2018-03-30 18:31:07 +00002415Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2416 if (CGM.getLangOpts().OpenMPSimd)
2417 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002418 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2419 isDeclareTargetDeclaration(VD);
2420 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2421 SmallString<64> PtrName;
2422 {
2423 llvm::raw_svector_ostream OS(PtrName);
2424 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2425 }
2426 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2427 if (!Ptr) {
2428 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2429 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2430 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002431 if (!CGM.getLangOpts().OpenMPIsDevice) {
2432 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2433 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2434 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2435 }
2436 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2437 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002438 }
2439 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2440 }
2441 return Address::invalid();
2442}
2443
Alexey Bataev97720002014-11-11 04:05:39 +00002444llvm::Constant *
2445CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002446 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2447 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002448 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002449 std::string Suffix = getName({"cache", ""});
2450 return getOrCreateInternalVariable(
2451 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002452}
2453
John McCall7f416cc2015-09-08 08:05:57 +00002454Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2455 const VarDecl *VD,
2456 Address VDAddr,
2457 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002458 if (CGM.getLangOpts().OpenMPUseTLS &&
2459 CGM.getContext().getTargetInfo().isTLSSupported())
2460 return VDAddr;
2461
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002462 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002463 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002464 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2465 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002466 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2467 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002468 return Address(CGF.EmitRuntimeCall(
2469 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2470 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002471}
2472
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002473void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002474 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002475 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2476 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2477 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002478 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002479 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002480 OMPLoc);
2481 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2482 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002483 llvm::Value *Args[] = {
2484 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2485 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002486 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002487 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002488}
2489
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002490llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002491 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002492 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002493 if (CGM.getLangOpts().OpenMPUseTLS &&
2494 CGM.getContext().getTargetInfo().isTLSSupported())
2495 return nullptr;
2496
Alexey Bataev97720002014-11-11 04:05:39 +00002497 VD = VD->getDefinition(CGM.getContext());
2498 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2499 ThreadPrivateWithDefinition.insert(VD);
2500 QualType ASTTy = VD->getType();
2501
2502 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002503 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002504 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2505 // Generate function that re-emits the declaration's initializer into the
2506 // threadprivate copy of the variable VD
2507 CodeGenFunction CtorCGF(CGM);
2508 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002509 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2510 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002511 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002512 Args.push_back(&Dst);
2513
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002514 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002515 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002516 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002517 std::string Name = getName({"__kmpc_global_ctor_", ""});
2518 llvm::Function *Fn =
2519 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002520 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002521 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002522 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002523 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002524 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002525 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002526 Arg = CtorCGF.Builder.CreateElementBitCast(
2527 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002528 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2529 /*IsInitializer=*/true);
2530 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002531 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002532 CGM.getContext().VoidPtrTy, Dst.getLocation());
2533 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2534 CtorCGF.FinishFunction();
2535 Ctor = Fn;
2536 }
2537 if (VD->getType().isDestructedType() != QualType::DK_none) {
2538 // Generate function that emits destructor call for the threadprivate copy
2539 // of the variable VD
2540 CodeGenFunction DtorCGF(CGM);
2541 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002542 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2543 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002544 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002545 Args.push_back(&Dst);
2546
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002547 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002548 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002549 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002550 std::string Name = getName({"__kmpc_global_dtor_", ""});
2551 llvm::Function *Fn =
2552 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002553 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002554 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002555 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002556 // Create a scope with an artificial location for the body of this function.
2557 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002558 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002559 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002560 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2561 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002562 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2563 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2564 DtorCGF.FinishFunction();
2565 Dtor = Fn;
2566 }
2567 // Do not emit init function if it is not required.
2568 if (!Ctor && !Dtor)
2569 return nullptr;
2570
2571 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002572 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2573 /*isVarArg=*/false)
2574 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002575 // Copying constructor for the threadprivate variable.
2576 // Must be NULL - reserved by runtime, but currently it requires that this
2577 // parameter is always NULL. Otherwise it fires assertion.
2578 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2579 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002580 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2581 /*isVarArg=*/false)
2582 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002583 Ctor = llvm::Constant::getNullValue(CtorTy);
2584 }
2585 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002586 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2587 /*isVarArg=*/false)
2588 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002589 Dtor = llvm::Constant::getNullValue(DtorTy);
2590 }
2591 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002592 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002593 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002594 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002595 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002596 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002597 CodeGenFunction InitCGF(CGM);
2598 FunctionArgList ArgList;
2599 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2600 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002601 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002602 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002603 InitCGF.FinishFunction();
2604 return InitFunction;
2605 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002606 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002607 }
2608 return nullptr;
2609}
2610
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002611/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002612/// consists of the file and device IDs as well as line number associated with
2613/// the relevant entry source location.
2614static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2615 unsigned &DeviceID, unsigned &FileID,
2616 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002617 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002618
2619 // The loc should be always valid and have a file ID (the user cannot use
2620 // #pragma directives in macros)
2621
2622 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002623
2624 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2625 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2626
2627 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002628 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2629 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2630 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002631
2632 DeviceID = ID.getDevice();
2633 FileID = ID.getFile();
2634 LineNum = PLoc.getLine();
2635}
2636
2637bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2638 llvm::GlobalVariable *Addr,
2639 bool PerformInit) {
2640 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2641 isDeclareTargetDeclaration(VD);
2642 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2643 return false;
2644 VD = VD->getDefinition(CGM.getContext());
2645 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2646 return CGM.getLangOpts().OpenMPIsDevice;
2647
2648 QualType ASTTy = VD->getType();
2649
2650 SourceLocation Loc = VD->getCanonicalDecl()->getLocStart();
2651 // Produce the unique prefix to identify the new target regions. We use
2652 // the source location of the variable declaration which we know to not
2653 // conflict with any target region.
2654 unsigned DeviceID;
2655 unsigned FileID;
2656 unsigned Line;
2657 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2658 SmallString<128> Buffer, Out;
2659 {
2660 llvm::raw_svector_ostream OS(Buffer);
2661 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2662 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2663 }
2664
2665 const Expr *Init = VD->getAnyInitializer();
2666 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2667 llvm::Constant *Ctor;
2668 llvm::Constant *ID;
2669 if (CGM.getLangOpts().OpenMPIsDevice) {
2670 // Generate function that re-emits the declaration's initializer into
2671 // the threadprivate copy of the variable VD
2672 CodeGenFunction CtorCGF(CGM);
2673
2674 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2675 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2676 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2677 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2678 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2679 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2680 FunctionArgList(), Loc, Loc);
2681 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2682 CtorCGF.EmitAnyExprToMem(Init,
2683 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2684 Init->getType().getQualifiers(),
2685 /*IsInitializer=*/true);
2686 CtorCGF.FinishFunction();
2687 Ctor = Fn;
2688 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002689 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002690 } else {
2691 Ctor = new llvm::GlobalVariable(
2692 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2693 llvm::GlobalValue::PrivateLinkage,
2694 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2695 ID = Ctor;
2696 }
2697
2698 // Register the information for the entry associated with the constructor.
2699 Out.clear();
2700 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2701 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002702 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002703 }
2704 if (VD->getType().isDestructedType() != QualType::DK_none) {
2705 llvm::Constant *Dtor;
2706 llvm::Constant *ID;
2707 if (CGM.getLangOpts().OpenMPIsDevice) {
2708 // Generate function that emits destructor call for the threadprivate
2709 // copy of the variable VD
2710 CodeGenFunction DtorCGF(CGM);
2711
2712 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2713 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2714 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2715 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2716 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2717 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2718 FunctionArgList(), Loc, Loc);
2719 // Create a scope with an artificial location for the body of this
2720 // function.
2721 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2722 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2723 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2724 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2725 DtorCGF.FinishFunction();
2726 Dtor = Fn;
2727 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002728 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002729 } else {
2730 Dtor = new llvm::GlobalVariable(
2731 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2732 llvm::GlobalValue::PrivateLinkage,
2733 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2734 ID = Dtor;
2735 }
2736 // Register the information for the entry associated with the destructor.
2737 Out.clear();
2738 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2739 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002740 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002741 }
2742 return CGM.getLangOpts().OpenMPIsDevice;
2743}
2744
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002745Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2746 QualType VarType,
2747 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002748 std::string Suffix = getName({"artificial", ""});
2749 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002750 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002751 llvm::Value *GAddr =
2752 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002753 llvm::Value *Args[] = {
2754 emitUpdateLocation(CGF, SourceLocation()),
2755 getThreadID(CGF, SourceLocation()),
2756 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2757 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2758 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002759 getOrCreateInternalVariable(
2760 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002761 return Address(
2762 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2763 CGF.EmitRuntimeCall(
2764 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2765 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2766 CGM.getPointerAlign());
2767}
2768
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002769void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2770 const RegionCodeGenTy &ThenGen,
2771 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002772 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2773
2774 // If the condition constant folds and can be elided, try to avoid emitting
2775 // the condition and the dead arm of the if/else.
2776 bool CondConstant;
2777 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002778 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002779 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002780 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002781 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002782 return;
2783 }
2784
2785 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2786 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002787 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2788 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2789 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002790 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2791
2792 // Emit the 'then' code.
2793 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002794 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002795 CGF.EmitBranch(ContBlock);
2796 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002797 // There is no need to emit line number for unconditional branch.
2798 (void)ApplyDebugLocation::CreateEmpty(CGF);
2799 CGF.EmitBlock(ElseBlock);
2800 ElseGen(CGF);
2801 // There is no need to emit line number for unconditional branch.
2802 (void)ApplyDebugLocation::CreateEmpty(CGF);
2803 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002804 // Emit the continuation block for code after the if.
2805 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002806}
2807
Alexey Bataev1d677132015-04-22 13:57:31 +00002808void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2809 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002810 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002811 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002812 if (!CGF.HaveInsertPoint())
2813 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002814 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002815 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2816 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002817 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002818 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002819 llvm::Value *Args[] = {
2820 RTLoc,
2821 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002822 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002823 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2824 RealArgs.append(std::begin(Args), std::end(Args));
2825 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2826
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002827 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002828 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2829 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002830 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2831 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002832 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2833 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002834 // Build calls:
2835 // __kmpc_serialized_parallel(&Loc, GTid);
2836 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002837 CGF.EmitRuntimeCall(
2838 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002839
Alexey Bataev1d677132015-04-22 13:57:31 +00002840 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002841 Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002842 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2843 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002844 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002845 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2846 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2847 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2848 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002849 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002850
Alexey Bataev1d677132015-04-22 13:57:31 +00002851 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002852 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002853 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002854 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2855 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002856 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002857 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002858 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002859 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002860 RegionCodeGenTy ThenRCG(ThenGen);
2861 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002862 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002863}
2864
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002865// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002866// thread-ID variable (it is passed in a first argument of the outlined function
2867// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2868// regular serial code region, get thread ID by calling kmp_int32
2869// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2870// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002871Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2872 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002873 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002874 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002875 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002876 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002877
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002878 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2879 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002880 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002881 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002882 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002883 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002884
2885 return ThreadIDTemp;
2886}
2887
Alexey Bataev97720002014-11-11 04:05:39 +00002888llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002889CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002890 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002891 SmallString<256> Buffer;
2892 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002893 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002894 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002895 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002896 if (Elem.second) {
2897 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002898 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002899 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002900 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002901
David Blaikie13156b62014-11-19 03:06:06 +00002902 return Elem.second = new llvm::GlobalVariable(
2903 CGM.getModule(), Ty, /*IsConstant*/ false,
2904 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2905 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002906}
2907
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002908llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002909 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2910 std::string Name = getName({Prefix, "var"});
2911 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002912}
2913
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002914namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002915/// Common pre(post)-action for different OpenMP constructs.
2916class CommonActionTy final : public PrePostActionTy {
2917 llvm::Value *EnterCallee;
2918 ArrayRef<llvm::Value *> EnterArgs;
2919 llvm::Value *ExitCallee;
2920 ArrayRef<llvm::Value *> ExitArgs;
2921 bool Conditional;
2922 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002923
2924public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002925 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2926 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2927 bool Conditional = false)
2928 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2929 ExitArgs(ExitArgs), Conditional(Conditional) {}
2930 void Enter(CodeGenFunction &CGF) override {
2931 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2932 if (Conditional) {
2933 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2934 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2935 ContBlock = CGF.createBasicBlock("omp_if.end");
2936 // Generate the branch (If-stmt)
2937 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2938 CGF.EmitBlock(ThenBlock);
2939 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002940 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002941 void Done(CodeGenFunction &CGF) {
2942 // Emit the rest of blocks/branches
2943 CGF.EmitBranch(ContBlock);
2944 CGF.EmitBlock(ContBlock, true);
2945 }
2946 void Exit(CodeGenFunction &CGF) override {
2947 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002948 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002949};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002950} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002951
2952void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2953 StringRef CriticalName,
2954 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002955 SourceLocation Loc, const Expr *Hint) {
2956 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002957 // CriticalOpGen();
2958 // __kmpc_end_critical(ident_t *, gtid, Lock);
2959 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002960 if (!CGF.HaveInsertPoint())
2961 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002962 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2963 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002964 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2965 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002966 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002967 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2968 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2969 }
2970 CommonActionTy Action(
2971 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2972 : OMPRTL__kmpc_critical),
2973 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2974 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002975 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002976}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002977
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002978void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002979 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002980 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002981 if (!CGF.HaveInsertPoint())
2982 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002983 // if(__kmpc_master(ident_t *, gtid)) {
2984 // MasterOpGen();
2985 // __kmpc_end_master(ident_t *, gtid);
2986 // }
2987 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002988 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002989 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2990 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2991 /*Conditional=*/true);
2992 MasterOpGen.setAction(Action);
2993 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2994 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002995}
2996
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002997void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2998 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002999 if (!CGF.HaveInsertPoint())
3000 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003001 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3002 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003003 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003004 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003005 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003006 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3007 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003008}
3009
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003010void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3011 const RegionCodeGenTy &TaskgroupOpGen,
3012 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003013 if (!CGF.HaveInsertPoint())
3014 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003015 // __kmpc_taskgroup(ident_t *, gtid);
3016 // TaskgroupOpGen();
3017 // __kmpc_end_taskgroup(ident_t *, gtid);
3018 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003019 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3020 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3021 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3022 Args);
3023 TaskgroupOpGen.setAction(Action);
3024 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003025}
3026
John McCall7f416cc2015-09-08 08:05:57 +00003027/// Given an array of pointers to variables, project the address of a
3028/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003029static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3030 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003031 // Pull out the pointer to the variable.
3032 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003033 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003034 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3035
3036 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003037 Addr = CGF.Builder.CreateElementBitCast(
3038 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003039 return Addr;
3040}
3041
Alexey Bataeva63048e2015-03-23 06:18:07 +00003042static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003043 CodeGenModule &CGM, llvm::Type *ArgsType,
3044 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003045 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3046 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003047 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003048 // void copy_func(void *LHSArg, void *RHSArg);
3049 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003050 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3051 ImplicitParamDecl::Other);
3052 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3053 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003054 Args.push_back(&LHSArg);
3055 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003056 const auto &CGFI =
3057 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003058 std::string Name =
3059 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3060 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3061 llvm::GlobalValue::InternalLinkage, Name,
3062 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003063 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003064 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003065 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003066 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003067 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003068 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003069 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3070 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3071 ArgsType), CGF.getPointerAlign());
3072 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3073 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3074 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003075 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3076 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3077 // ...
3078 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003079 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003080 const auto *DestVar =
3081 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003082 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3083
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003084 const auto *SrcVar =
3085 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003086 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3087
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003088 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003089 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003090 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003091 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003092 CGF.FinishFunction();
3093 return Fn;
3094}
3095
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003096void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003097 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003098 SourceLocation Loc,
3099 ArrayRef<const Expr *> CopyprivateVars,
3100 ArrayRef<const Expr *> SrcExprs,
3101 ArrayRef<const Expr *> DstExprs,
3102 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003103 if (!CGF.HaveInsertPoint())
3104 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003105 assert(CopyprivateVars.size() == SrcExprs.size() &&
3106 CopyprivateVars.size() == DstExprs.size() &&
3107 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003108 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003109 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003110 // if(__kmpc_single(ident_t *, gtid)) {
3111 // SingleOpGen();
3112 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003113 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003114 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003115 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3116 // <copy_func>, did_it);
3117
John McCall7f416cc2015-09-08 08:05:57 +00003118 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003119 if (!CopyprivateVars.empty()) {
3120 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003121 QualType KmpInt32Ty =
3122 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003123 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003124 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003125 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003126 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003127 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003128 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3129 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3130 /*Conditional=*/true);
3131 SingleOpGen.setAction(Action);
3132 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3133 if (DidIt.isValid()) {
3134 // did_it = 1;
3135 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3136 }
3137 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003138 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3139 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003140 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003141 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003142 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003143 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3144 /*IndexTypeQuals=*/0);
3145 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003146 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003147 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3148 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003149 Address Elem = CGF.Builder.CreateConstArrayGEP(
3150 CopyprivateList, I, CGF.getPointerSize());
3151 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003152 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003153 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3154 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003155 }
3156 // Build function that copies private values from single region to all other
3157 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003158 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003159 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003160 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003161 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003162 Address CL =
3163 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3164 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003165 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003166 llvm::Value *Args[] = {
3167 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3168 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003169 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003170 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003171 CpyFn, // void (*) (void *, void *) <copy_func>
3172 DidItVal // i32 did_it
3173 };
3174 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3175 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003176}
3177
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003178void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3179 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003180 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003181 if (!CGF.HaveInsertPoint())
3182 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003183 // __kmpc_ordered(ident_t *, gtid);
3184 // OrderedOpGen();
3185 // __kmpc_end_ordered(ident_t *, gtid);
3186 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003187 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003188 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003189 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3190 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3191 Args);
3192 OrderedOpGen.setAction(Action);
3193 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3194 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003195 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003196 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003197}
3198
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003199void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003200 OpenMPDirectiveKind Kind, bool EmitChecks,
3201 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003202 if (!CGF.HaveInsertPoint())
3203 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003204 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003205 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003206 unsigned Flags;
3207 if (Kind == OMPD_for)
3208 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3209 else if (Kind == OMPD_sections)
3210 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3211 else if (Kind == OMPD_single)
3212 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3213 else if (Kind == OMPD_barrier)
3214 Flags = OMP_IDENT_BARRIER_EXPL;
3215 else
3216 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003217 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3218 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003219 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3220 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003221 if (auto *OMPRegionInfo =
3222 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003223 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003224 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003225 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003226 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003227 // if (__kmpc_cancel_barrier()) {
3228 // exit from construct;
3229 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003230 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3231 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3232 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003233 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3234 CGF.EmitBlock(ExitBB);
3235 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003236 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003237 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003238 CGF.EmitBranchThroughCleanup(CancelDestination);
3239 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3240 }
3241 return;
3242 }
3243 }
3244 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003245}
3246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003247/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003248static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003249 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003250 switch (ScheduleKind) {
3251 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003252 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3253 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003254 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003255 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003256 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003257 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003258 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003259 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3260 case OMPC_SCHEDULE_auto:
3261 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003262 case OMPC_SCHEDULE_unknown:
3263 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003264 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003265 }
3266 llvm_unreachable("Unexpected runtime schedule");
3267}
3268
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003269/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003270static OpenMPSchedType
3271getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3272 // only static is allowed for dist_schedule
3273 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3274}
3275
Alexander Musmanc6388682014-12-15 07:07:06 +00003276bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3277 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003278 OpenMPSchedType Schedule =
3279 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003280 return Schedule == OMP_sch_static;
3281}
3282
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003283bool CGOpenMPRuntime::isStaticNonchunked(
3284 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003285 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003286 return Schedule == OMP_dist_sch_static;
3287}
3288
3289
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003290bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003291 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003292 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003293 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3294 return Schedule != OMP_sch_static;
3295}
3296
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003297static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3298 OpenMPScheduleClauseModifier M1,
3299 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003300 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003301 switch (M1) {
3302 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003303 Modifier = OMP_sch_modifier_monotonic;
3304 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003305 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003306 Modifier = OMP_sch_modifier_nonmonotonic;
3307 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003308 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003309 if (Schedule == OMP_sch_static_chunked)
3310 Schedule = OMP_sch_static_balanced_chunked;
3311 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003312 case OMPC_SCHEDULE_MODIFIER_last:
3313 case OMPC_SCHEDULE_MODIFIER_unknown:
3314 break;
3315 }
3316 switch (M2) {
3317 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003318 Modifier = OMP_sch_modifier_monotonic;
3319 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003320 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003321 Modifier = OMP_sch_modifier_nonmonotonic;
3322 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003323 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003324 if (Schedule == OMP_sch_static_chunked)
3325 Schedule = OMP_sch_static_balanced_chunked;
3326 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003327 case OMPC_SCHEDULE_MODIFIER_last:
3328 case OMPC_SCHEDULE_MODIFIER_unknown:
3329 break;
3330 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003331 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003332}
3333
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003334void CGOpenMPRuntime::emitForDispatchInit(
3335 CodeGenFunction &CGF, SourceLocation Loc,
3336 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3337 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003338 if (!CGF.HaveInsertPoint())
3339 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003340 OpenMPSchedType Schedule = getRuntimeSchedule(
3341 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003342 assert(Ordered ||
3343 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003344 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3345 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003346 // Call __kmpc_dispatch_init(
3347 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3348 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3349 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003350
John McCall7f416cc2015-09-08 08:05:57 +00003351 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003352 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3353 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003354 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003355 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3356 CGF.Builder.getInt32(addMonoNonMonoModifier(
3357 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003358 DispatchValues.LB, // Lower
3359 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003360 CGF.Builder.getIntN(IVSize, 1), // Stride
3361 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003362 };
3363 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3364}
3365
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003366static void emitForStaticInitCall(
3367 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3368 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3369 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003370 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003371 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003372 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003373
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003374 assert(!Values.Ordered);
3375 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3376 Schedule == OMP_sch_static_balanced_chunked ||
3377 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3378 Schedule == OMP_dist_sch_static ||
3379 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003380
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003381 // Call __kmpc_for_static_init(
3382 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3383 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3384 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3385 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3386 llvm::Value *Chunk = Values.Chunk;
3387 if (Chunk == nullptr) {
3388 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3389 Schedule == OMP_dist_sch_static) &&
3390 "expected static non-chunked schedule");
3391 // If the Chunk was not specified in the clause - use default value 1.
3392 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3393 } else {
3394 assert((Schedule == OMP_sch_static_chunked ||
3395 Schedule == OMP_sch_static_balanced_chunked ||
3396 Schedule == OMP_ord_static_chunked ||
3397 Schedule == OMP_dist_sch_static_chunked) &&
3398 "expected static chunked schedule");
3399 }
3400 llvm::Value *Args[] = {
3401 UpdateLocation,
3402 ThreadId,
3403 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3404 M2)), // Schedule type
3405 Values.IL.getPointer(), // &isLastIter
3406 Values.LB.getPointer(), // &LB
3407 Values.UB.getPointer(), // &UB
3408 Values.ST.getPointer(), // &Stride
3409 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3410 Chunk // Chunk
3411 };
3412 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003413}
3414
John McCall7f416cc2015-09-08 08:05:57 +00003415void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3416 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003417 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003418 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003419 const StaticRTInput &Values) {
3420 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3421 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3422 assert(isOpenMPWorksharingDirective(DKind) &&
3423 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003424 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003425 isOpenMPLoopDirective(DKind)
3426 ? OMP_IDENT_WORK_LOOP
3427 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003428 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3429 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003430 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003431 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003432 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003433}
John McCall7f416cc2015-09-08 08:05:57 +00003434
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003435void CGOpenMPRuntime::emitDistributeStaticInit(
3436 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003437 OpenMPDistScheduleClauseKind SchedKind,
3438 const CGOpenMPRuntime::StaticRTInput &Values) {
3439 OpenMPSchedType ScheduleNum =
3440 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003441 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003442 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003443 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3444 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003445 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003446 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3447 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003448 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003449}
3450
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003451void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003452 SourceLocation Loc,
3453 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003454 if (!CGF.HaveInsertPoint())
3455 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003456 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003457 llvm::Value *Args[] = {
3458 emitUpdateLocation(CGF, Loc,
3459 isOpenMPDistributeDirective(DKind)
3460 ? OMP_IDENT_WORK_DISTRIBUTE
3461 : isOpenMPLoopDirective(DKind)
3462 ? OMP_IDENT_WORK_LOOP
3463 : OMP_IDENT_WORK_SECTIONS),
3464 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003465 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3466 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003467}
3468
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003469void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3470 SourceLocation Loc,
3471 unsigned IVSize,
3472 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003473 if (!CGF.HaveInsertPoint())
3474 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003475 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003476 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003477 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3478}
3479
Alexander Musman92bdaab2015-03-12 13:37:50 +00003480llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3481 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003482 bool IVSigned, Address IL,
3483 Address LB, Address UB,
3484 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003485 // Call __kmpc_dispatch_next(
3486 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3487 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3488 // kmp_int[32|64] *p_stride);
3489 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003490 emitUpdateLocation(CGF, Loc),
3491 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003492 IL.getPointer(), // &isLastIter
3493 LB.getPointer(), // &Lower
3494 UB.getPointer(), // &Upper
3495 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003496 };
3497 llvm::Value *Call =
3498 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3499 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003500 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003501 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003502}
3503
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003504void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3505 llvm::Value *NumThreads,
3506 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003507 if (!CGF.HaveInsertPoint())
3508 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003509 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3510 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003511 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003512 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003513 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3514 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003515}
3516
Alexey Bataev7f210c62015-06-18 13:40:03 +00003517void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3518 OpenMPProcBindClauseKind ProcBind,
3519 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003520 if (!CGF.HaveInsertPoint())
3521 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003522 // Constants for proc bind value accepted by the runtime.
3523 enum ProcBindTy {
3524 ProcBindFalse = 0,
3525 ProcBindTrue,
3526 ProcBindMaster,
3527 ProcBindClose,
3528 ProcBindSpread,
3529 ProcBindIntel,
3530 ProcBindDefault
3531 } RuntimeProcBind;
3532 switch (ProcBind) {
3533 case OMPC_PROC_BIND_master:
3534 RuntimeProcBind = ProcBindMaster;
3535 break;
3536 case OMPC_PROC_BIND_close:
3537 RuntimeProcBind = ProcBindClose;
3538 break;
3539 case OMPC_PROC_BIND_spread:
3540 RuntimeProcBind = ProcBindSpread;
3541 break;
3542 case OMPC_PROC_BIND_unknown:
3543 llvm_unreachable("Unsupported proc_bind value.");
3544 }
3545 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3546 llvm::Value *Args[] = {
3547 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3548 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3549 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3550}
3551
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003552void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3553 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003554 if (!CGF.HaveInsertPoint())
3555 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003556 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003557 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3558 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003559}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003560
Alexey Bataev62b63b12015-03-10 07:28:44 +00003561namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003562/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003563enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003564 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003565 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003566 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003567 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003568 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003569 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003570 /// Function with call of destructors for private variables.
3571 Data1,
3572 /// Task priority.
3573 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003574 /// (Taskloops only) Lower bound.
3575 KmpTaskTLowerBound,
3576 /// (Taskloops only) Upper bound.
3577 KmpTaskTUpperBound,
3578 /// (Taskloops only) Stride.
3579 KmpTaskTStride,
3580 /// (Taskloops only) Is last iteration flag.
3581 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003582 /// (Taskloops only) Reduction data.
3583 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003584};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003585} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003586
Samuel Antaoee8fb302016-01-06 13:42:12 +00003587bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003588 return OffloadEntriesTargetRegion.empty() &&
3589 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003590}
3591
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003592/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003593void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3594 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3595 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003596 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003597 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3598 "only required for the device "
3599 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003600 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003601 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003602 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003603 ++OffloadingEntriesNum;
3604}
3605
3606void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3607 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3608 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003609 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003610 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003611 // If we are emitting code for a target, the entry is already initialized,
3612 // only has to be registered.
3613 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003614 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3615 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3616 DiagnosticsEngine::Error,
3617 "Unable to find target region on line '%0' in the device code.");
3618 CGM.getDiags().Report(DiagID) << LineNum;
3619 return;
3620 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003621 auto &Entry =
3622 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003623 assert(Entry.isValid() && "Entry not initialized!");
3624 Entry.setAddress(Addr);
3625 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003626 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003627 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003628 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003629 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003630 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003631 }
3632}
3633
3634bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003635 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3636 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003637 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3638 if (PerDevice == OffloadEntriesTargetRegion.end())
3639 return false;
3640 auto PerFile = PerDevice->second.find(FileID);
3641 if (PerFile == PerDevice->second.end())
3642 return false;
3643 auto PerParentName = PerFile->second.find(ParentName);
3644 if (PerParentName == PerFile->second.end())
3645 return false;
3646 auto PerLine = PerParentName->second.find(LineNum);
3647 if (PerLine == PerParentName->second.end())
3648 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003649 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003650 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003651 return false;
3652 return true;
3653}
3654
3655void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3656 const OffloadTargetRegionEntryInfoActTy &Action) {
3657 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003658 for (const auto &D : OffloadEntriesTargetRegion)
3659 for (const auto &F : D.second)
3660 for (const auto &P : F.second)
3661 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003662 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003663}
3664
Alexey Bataev03f270c2018-03-30 18:31:07 +00003665void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3666 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3667 OMPTargetGlobalVarEntryKind Flags,
3668 unsigned Order) {
3669 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3670 "only required for the device "
3671 "code generation.");
3672 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3673 ++OffloadingEntriesNum;
3674}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003675
Alexey Bataev03f270c2018-03-30 18:31:07 +00003676void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3677 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3678 CharUnits VarSize,
3679 OMPTargetGlobalVarEntryKind Flags,
3680 llvm::GlobalValue::LinkageTypes Linkage) {
3681 if (CGM.getLangOpts().OpenMPIsDevice) {
3682 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3683 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3684 "Entry not initialized!");
3685 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3686 "Resetting with the new address.");
3687 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3688 return;
3689 Entry.setAddress(Addr);
3690 Entry.setVarSize(VarSize);
3691 Entry.setLinkage(Linkage);
3692 } else {
3693 if (hasDeviceGlobalVarEntryInfo(VarName))
3694 return;
3695 OffloadEntriesDeviceGlobalVar.try_emplace(
3696 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3697 ++OffloadingEntriesNum;
3698 }
3699}
3700
3701void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3702 actOnDeviceGlobalVarEntriesInfo(
3703 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3704 // Scan all target region entries and perform the provided action.
3705 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3706 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003707}
3708
3709llvm::Function *
3710CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003711 // If we don't have entries or if we are emitting code for the device, we
3712 // don't need to do anything.
3713 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3714 return nullptr;
3715
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003716 llvm::Module &M = CGM.getModule();
3717 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003718
3719 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003720 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003721
3722 // We should be creating an offloading descriptor only if there are devices
3723 // specified.
3724 assert(!Devices.empty() && "No OpenMP offloading devices??");
3725
3726 // Create the external variables that will point to the begin and end of the
3727 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003728 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003729 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003730 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003731 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003732 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003733 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003734 EntriesBeginName);
3735 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3736 auto *HostEntriesEnd =
3737 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3738 llvm::GlobalValue::ExternalLinkage,
3739 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003740
3741 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003742 auto *DeviceImageTy = cast<llvm::StructType>(
3743 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003744 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003745 ConstantArrayBuilder DeviceImagesEntries =
3746 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003747
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003748 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003749 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003750 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003751 auto *ImgBegin = new llvm::GlobalVariable(
3752 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003753 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3754 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003755 auto *ImgEnd = new llvm::GlobalVariable(
3756 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003757 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003758
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003759 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3760 HostEntriesEnd};
3761 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3762 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003763 }
3764
3765 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003766 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003767 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003768 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3769 CGM.getPointerAlign(),
3770 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003771 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003772
3773 // This is a Zero array to be used in the creation of the constant expressions
3774 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3775 llvm::Constant::getNullValue(CGM.Int32Ty)};
3776
3777 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003778 llvm::Constant *Data[] = {
3779 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3780 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3781 DeviceImages, Index),
3782 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003783 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003784 llvm::GlobalVariable *Desc = createConstantGlobalStruct(
Alexey Bataev18fa2322018-05-02 14:20:50 +00003785 CGM, getTgtBinaryDescriptorQTy(), Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003786
3787 // Emit code to register or unregister the descriptor at execution
3788 // startup or closing, respectively.
3789
Alexey Bataev03f270c2018-03-30 18:31:07 +00003790 llvm::Function *UnRegFn;
3791 {
3792 FunctionArgList Args;
3793 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3794 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003795
Alexey Bataev03f270c2018-03-30 18:31:07 +00003796 CodeGenFunction CGF(CGM);
3797 // Disable debug info for global (de-)initializer because they are not part
3798 // of some particular construct.
3799 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003800 const auto &FI =
3801 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3802 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003803 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3804 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003805 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3806 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3807 Desc);
3808 CGF.FinishFunction();
3809 }
3810 llvm::Function *RegFn;
3811 {
3812 CodeGenFunction CGF(CGM);
3813 // Disable debug info for global (de-)initializer because they are not part
3814 // of some particular construct.
3815 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003816 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003817 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003818 std::string Descriptor = getName({"omp_offloading", "descriptor_reg"});
3819 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003820 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3821 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3822 // Create a variable to drive the registration and unregistration of the
3823 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3824 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3825 SourceLocation(), nullptr, C.CharTy,
3826 ImplicitParamDecl::Other);
3827 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3828 CGF.FinishFunction();
3829 }
George Rokos29d0f002017-05-27 03:03:13 +00003830 if (CGM.supportsCOMDAT()) {
3831 // It is sufficient to call registration function only once, so create a
3832 // COMDAT group for registration/unregistration functions and associated
3833 // data. That would reduce startup time and code size. Registration
3834 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003835 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003836 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3837 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3838 RegFn->setComdat(ComdatKey);
3839 UnRegFn->setComdat(ComdatKey);
3840 DeviceImages->setComdat(ComdatKey);
3841 Desc->setComdat(ComdatKey);
3842 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003843 return RegFn;
3844}
3845
Alexey Bataev03f270c2018-03-30 18:31:07 +00003846void CGOpenMPRuntime::createOffloadEntry(
3847 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3848 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003849 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003850 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003851 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003852
3853 // Create constant string with the name.
3854 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3855
Alexey Bataev18fa2322018-05-02 14:20:50 +00003856 std::string StringName = getName({"omp_offloading", "entry_name"});
3857 auto *Str = new llvm::GlobalVariable(
3858 M, StrPtrInit->getType(), /*isConstant=*/true,
3859 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003860 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003861
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003862 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3863 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3864 llvm::ConstantInt::get(CGM.SizeTy, Size),
3865 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3866 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003867 std::string EntryName = getName({"omp_offloading", "entry", ""});
Alexey Bataev9a700172018-05-08 14:16:57 +00003868 llvm::GlobalVariable *Entry = createConstantGlobalStruct(
3869 CGM, getTgtOffloadEntryQTy(), Data, Twine(EntryName).concat(Name),
3870 llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003871
3872 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003873 std::string Section = getName({"omp_offloading", "entries"});
3874 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003875}
3876
3877void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3878 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003879 // can easily figure out what to emit. The produced metadata looks like
3880 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003881 //
3882 // !omp_offload.info = !{!1, ...}
3883 //
3884 // Right now we only generate metadata for function that contain target
3885 // regions.
3886
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003887 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003888 if (OffloadEntriesInfoManager.empty())
3889 return;
3890
3891 llvm::Module &M = CGM.getModule();
3892 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003893 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003894 OrderedEntries(OffloadEntriesInfoManager.size());
3895
Simon Pilgrim2c518802017-03-30 14:13:19 +00003896 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003897 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003898 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003899 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003900 };
3901
Alexey Bataev03f270c2018-03-30 18:31:07 +00003902 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3903
3904 // Create the offloading info metadata node.
3905 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003906
3907 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003908 auto &&TargetRegionMetadataEmitter =
3909 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3910 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3911 unsigned Line,
3912 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3913 // Generate metadata for target regions. Each entry of this metadata
3914 // contains:
3915 // - Entry 0 -> Kind of this type of metadata (0).
3916 // - Entry 1 -> Device ID of the file where the entry was identified.
3917 // - Entry 2 -> File ID of the file where the entry was identified.
3918 // - Entry 3 -> Mangled name of the function where the entry was
3919 // identified.
3920 // - Entry 4 -> Line in the file where the entry was identified.
3921 // - Entry 5 -> Order the entry was created.
3922 // The first element of the metadata node is the kind.
3923 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3924 GetMDInt(FileID), GetMDString(ParentName),
3925 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003926
Alexey Bataev03f270c2018-03-30 18:31:07 +00003927 // Save this entry in the right position of the ordered entries array.
3928 OrderedEntries[E.getOrder()] = &E;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003929
Alexey Bataev03f270c2018-03-30 18:31:07 +00003930 // Add metadata to the named metadata node.
3931 MD->addOperand(llvm::MDNode::get(C, Ops));
3932 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003933
3934 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3935 TargetRegionMetadataEmitter);
3936
Alexey Bataev03f270c2018-03-30 18:31:07 +00003937 // Create function that emits metadata for each device global variable entry;
3938 auto &&DeviceGlobalVarMetadataEmitter =
3939 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3940 MD](StringRef MangledName,
3941 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3942 &E) {
3943 // Generate metadata for global variables. Each entry of this metadata
3944 // contains:
3945 // - Entry 0 -> Kind of this type of metadata (1).
3946 // - Entry 1 -> Mangled name of the variable.
3947 // - Entry 2 -> Declare target kind.
3948 // - Entry 3 -> Order the entry was created.
3949 // The first element of the metadata node is the kind.
3950 llvm::Metadata *Ops[] = {
3951 GetMDInt(E.getKind()), GetMDString(MangledName),
3952 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3953
3954 // Save this entry in the right position of the ordered entries array.
3955 OrderedEntries[E.getOrder()] = &E;
3956
3957 // Add metadata to the named metadata node.
3958 MD->addOperand(llvm::MDNode::get(C, Ops));
3959 };
3960
3961 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3962 DeviceGlobalVarMetadataEmitter);
3963
3964 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003965 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003966 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003967 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3968 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003969 if (!CE->getID() || !CE->getAddress()) {
3970 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3971 DiagnosticsEngine::Error,
3972 "Offloading entry for target region is incorect: either the "
3973 "address or the ID is invalid.");
3974 CGM.getDiags().Report(DiagID);
3975 continue;
3976 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00003977 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00003978 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3979 } else if (const auto *CE =
3980 dyn_cast<OffloadEntriesInfoManagerTy::
3981 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003982 if (!CE->getAddress()) {
3983 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3984 DiagnosticsEngine::Error,
3985 "Offloading entry for declare target varible is inccorect: the "
3986 "address is invalid.");
3987 CGM.getDiags().Report(DiagID);
3988 continue;
3989 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003990 createOffloadEntry(CE->getAddress(), CE->getAddress(),
3991 CE->getVarSize().getQuantity(), CE->getFlags(),
3992 CE->getLinkage());
3993 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003994 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003995 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003996 }
3997}
3998
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003999/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004000/// metadata.
4001void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4002 // If we are in target mode, load the metadata from the host IR. This code has
4003 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4004
4005 if (!CGM.getLangOpts().OpenMPIsDevice)
4006 return;
4007
4008 if (CGM.getLangOpts().OMPHostIRFile.empty())
4009 return;
4010
4011 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004012 if (auto EC = Buf.getError()) {
4013 CGM.getDiags().Report(diag::err_cannot_open_file)
4014 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004015 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004016 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004017
4018 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004019 auto ME = expectedToErrorOrAndEmitErrors(
4020 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004021
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004022 if (auto EC = ME.getError()) {
4023 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4024 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4025 CGM.getDiags().Report(DiagID)
4026 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004027 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004028 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004029
4030 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4031 if (!MD)
4032 return;
4033
George Burgess IV00f70bd2018-03-01 05:43:23 +00004034 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004035 auto &&GetMDInt = [MN](unsigned Idx) {
4036 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004037 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4038 };
4039
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004040 auto &&GetMDString = [MN](unsigned Idx) {
4041 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004042 return V->getString();
4043 };
4044
Alexey Bataev03f270c2018-03-30 18:31:07 +00004045 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004046 default:
4047 llvm_unreachable("Unexpected metadata!");
4048 break;
4049 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004050 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004051 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004052 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4053 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4054 /*Order=*/GetMDInt(5));
4055 break;
4056 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4057 OffloadingEntryInfoDeviceGlobalVar:
4058 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4059 /*MangledName=*/GetMDString(1),
4060 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4061 /*Flags=*/GetMDInt(2)),
4062 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004063 break;
4064 }
4065 }
4066}
4067
Alexey Bataev62b63b12015-03-10 07:28:44 +00004068void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4069 if (!KmpRoutineEntryPtrTy) {
4070 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004071 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004072 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4073 FunctionProtoType::ExtProtoInfo EPI;
4074 KmpRoutineEntryPtrQTy = C.getPointerType(
4075 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4076 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4077 }
4078}
4079
Samuel Antaoee8fb302016-01-06 13:42:12 +00004080QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004081 // Make sure the type of the entry is already created. This is the type we
4082 // have to create:
4083 // struct __tgt_offload_entry{
4084 // void *addr; // Pointer to the offload entry info.
4085 // // (function or global)
4086 // char *name; // Name of the function or global.
4087 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004088 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4089 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004090 // };
4091 if (TgtOffloadEntryQTy.isNull()) {
4092 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004093 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004094 RD->startDefinition();
4095 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4096 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4097 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004098 addFieldToRecordDecl(
4099 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4100 addFieldToRecordDecl(
4101 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004102 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004103 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004104 TgtOffloadEntryQTy = C.getRecordType(RD);
4105 }
4106 return TgtOffloadEntryQTy;
4107}
4108
4109QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4110 // These are the types we need to build:
4111 // struct __tgt_device_image{
4112 // void *ImageStart; // Pointer to the target code start.
4113 // void *ImageEnd; // Pointer to the target code end.
4114 // // We also add the host entries to the device image, as it may be useful
4115 // // for the target runtime to have access to that information.
4116 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4117 // // the entries.
4118 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4119 // // entries (non inclusive).
4120 // };
4121 if (TgtDeviceImageQTy.isNull()) {
4122 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004123 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004124 RD->startDefinition();
4125 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4126 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4127 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4128 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4129 RD->completeDefinition();
4130 TgtDeviceImageQTy = C.getRecordType(RD);
4131 }
4132 return TgtDeviceImageQTy;
4133}
4134
4135QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4136 // struct __tgt_bin_desc{
4137 // int32_t NumDevices; // Number of devices supported.
4138 // __tgt_device_image *DeviceImages; // Arrays of device images
4139 // // (one per device).
4140 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4141 // // entries.
4142 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4143 // // entries (non inclusive).
4144 // };
4145 if (TgtBinaryDescriptorQTy.isNull()) {
4146 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004147 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004148 RD->startDefinition();
4149 addFieldToRecordDecl(
4150 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4151 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4152 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4153 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4154 RD->completeDefinition();
4155 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4156 }
4157 return TgtBinaryDescriptorQTy;
4158}
4159
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004160namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004161struct PrivateHelpersTy {
4162 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4163 const VarDecl *PrivateElemInit)
4164 : Original(Original), PrivateCopy(PrivateCopy),
4165 PrivateElemInit(PrivateElemInit) {}
4166 const VarDecl *Original;
4167 const VarDecl *PrivateCopy;
4168 const VarDecl *PrivateElemInit;
4169};
4170typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004171} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004172
Alexey Bataev9e034042015-05-05 04:05:12 +00004173static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004174createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004175 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004176 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004177 // Build struct .kmp_privates_t. {
4178 // /* private vars */
4179 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004180 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004181 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004182 for (const auto &Pair : Privates) {
4183 const VarDecl *VD = Pair.second.Original;
4184 QualType Type = VD->getType().getNonReferenceType();
4185 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004186 if (VD->hasAttrs()) {
4187 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4188 E(VD->getAttrs().end());
4189 I != E; ++I)
4190 FD->addAttr(*I);
4191 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004192 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004193 RD->completeDefinition();
4194 return RD;
4195 }
4196 return nullptr;
4197}
4198
Alexey Bataev9e034042015-05-05 04:05:12 +00004199static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004200createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4201 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004202 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004203 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004204 // Build struct kmp_task_t {
4205 // void * shareds;
4206 // kmp_routine_entry_t routine;
4207 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004208 // kmp_cmplrdata_t data1;
4209 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004210 // For taskloops additional fields:
4211 // kmp_uint64 lb;
4212 // kmp_uint64 ub;
4213 // kmp_int64 st;
4214 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004215 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004216 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004217 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004218 UD->startDefinition();
4219 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4220 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4221 UD->completeDefinition();
4222 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004223 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004224 RD->startDefinition();
4225 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4226 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4227 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004228 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4229 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004230 if (isOpenMPTaskLoopDirective(Kind)) {
4231 QualType KmpUInt64Ty =
4232 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4233 QualType KmpInt64Ty =
4234 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4235 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4236 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4237 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4238 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004239 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004240 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004241 RD->completeDefinition();
4242 return RD;
4243}
4244
4245static RecordDecl *
4246createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004247 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004248 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004249 // Build struct kmp_task_t_with_privates {
4250 // kmp_task_t task_data;
4251 // .kmp_privates_t. privates;
4252 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004253 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004254 RD->startDefinition();
4255 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004256 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004257 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004258 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004259 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004260}
4261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004262/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004263/// argument.
4264/// \code
4265/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004266/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004267/// For taskloops:
4268/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004269/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004270/// return 0;
4271/// }
4272/// \endcode
4273static llvm::Value *
4274emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004275 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4276 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004277 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004278 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4279 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004280 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004281 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004282 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4283 ImplicitParamDecl::Other);
4284 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4285 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4286 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004287 Args.push_back(&GtidArg);
4288 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004289 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004290 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004291 llvm::FunctionType *TaskEntryTy =
4292 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004293 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4294 auto *TaskEntry = llvm::Function::Create(
4295 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004296 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004297 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004298 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004299 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4300 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004301
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004302 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004303 // tt,
4304 // For taskloops:
4305 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4306 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004307 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004308 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004309 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4310 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4311 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004312 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004313 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004314 LValue Base =
4315 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004316 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004317 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004318 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4319 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004320
4321 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004322 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4323 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004324 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004325 CGF.ConvertTypeForMem(SharedsPtrTy));
4326
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004327 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4328 llvm::Value *PrivatesParam;
4329 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004330 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004331 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004332 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004333 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004334 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004335 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004336
Alexey Bataev7292c292016-04-25 12:22:29 +00004337 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4338 TaskPrivatesMap,
4339 CGF.Builder
4340 .CreatePointerBitCastOrAddrSpaceCast(
4341 TDBase.getAddress(), CGF.VoidPtrTy)
4342 .getPointer()};
4343 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4344 std::end(CommonArgs));
4345 if (isOpenMPTaskLoopDirective(Kind)) {
4346 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004347 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4348 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004349 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004350 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4351 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004352 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004353 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4354 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004355 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004356 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4357 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004358 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004359 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4360 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004361 CallArgs.push_back(LBParam);
4362 CallArgs.push_back(UBParam);
4363 CallArgs.push_back(StParam);
4364 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004365 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004366 }
4367 CallArgs.push_back(SharedsParam);
4368
Alexey Bataev3c595a62017-08-14 15:01:03 +00004369 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4370 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004371 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4372 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004373 CGF.FinishFunction();
4374 return TaskEntry;
4375}
4376
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004377static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4378 SourceLocation Loc,
4379 QualType KmpInt32Ty,
4380 QualType KmpTaskTWithPrivatesPtrQTy,
4381 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004382 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004383 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004384 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4385 ImplicitParamDecl::Other);
4386 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4387 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4388 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004389 Args.push_back(&GtidArg);
4390 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004391 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004392 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004393 llvm::FunctionType *DestructorFnTy =
4394 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004395 std::string Name =
4396 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004397 auto *DestructorFn =
4398 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004399 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004400 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004401 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004402 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004403 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004404 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004405 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004406
Alexey Bataev31300ed2016-02-04 11:27:03 +00004407 LValue Base = CGF.EmitLoadOfPointerLValue(
4408 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4409 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004410 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004411 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4412 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004413 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004414 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004415 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004416 if (QualType::DestructionKind DtorKind =
4417 Field->getType().isDestructedType()) {
4418 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004419 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4420 }
4421 }
4422 CGF.FinishFunction();
4423 return DestructorFn;
4424}
4425
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004426/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004427/// firstprivate variables.
4428/// \code
4429/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4430/// **noalias priv1,..., <tyn> **noalias privn) {
4431/// *priv1 = &.privates.priv1;
4432/// ...;
4433/// *privn = &.privates.privn;
4434/// }
4435/// \endcode
4436static llvm::Value *
4437emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004438 ArrayRef<const Expr *> PrivateVars,
4439 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004440 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004441 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004442 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004443 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004444 FunctionArgList Args;
4445 ImplicitParamDecl TaskPrivatesArg(
4446 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004447 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4448 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004449 Args.push_back(&TaskPrivatesArg);
4450 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4451 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004452 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004453 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004454 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4455 C.getPointerType(C.getPointerType(E->getType()))
4456 .withConst()
4457 .withRestrict(),
4458 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004459 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004460 PrivateVarsPos[VD] = Counter;
4461 ++Counter;
4462 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004463 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004464 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004465 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4466 C.getPointerType(C.getPointerType(E->getType()))
4467 .withConst()
4468 .withRestrict(),
4469 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004470 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004471 PrivateVarsPos[VD] = Counter;
4472 ++Counter;
4473 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004474 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004475 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004476 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4477 C.getPointerType(C.getPointerType(E->getType()))
4478 .withConst()
4479 .withRestrict(),
4480 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004481 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004482 PrivateVarsPos[VD] = Counter;
4483 ++Counter;
4484 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004485 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004486 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004487 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004488 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004489 std::string Name =
4490 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004491 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004492 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4493 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004494 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004495 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004496 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004497 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004498 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004499 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004500 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004501 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004502
4503 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004504 LValue Base = CGF.EmitLoadOfPointerLValue(
4505 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4506 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004507 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004508 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004509 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4510 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4511 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4512 LValue RefLVal =
4513 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4514 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004515 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004516 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004517 ++Counter;
4518 }
4519 CGF.FinishFunction();
4520 return TaskPrivatesMap;
4521}
4522
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004523static bool stable_sort_comparator(const PrivateDataTy P1,
4524 const PrivateDataTy P2) {
4525 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004526}
4527
Alexey Bataevf93095a2016-05-05 08:46:22 +00004528/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004529static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004530 const OMPExecutableDirective &D,
4531 Address KmpTaskSharedsPtr, LValue TDBase,
4532 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4533 QualType SharedsTy, QualType SharedsPtrTy,
4534 const OMPTaskDataTy &Data,
4535 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004536 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004537 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4538 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004539 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4540 ? OMPD_taskloop
4541 : OMPD_task;
4542 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4543 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004544 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004545 bool IsTargetTask =
4546 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4547 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4548 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4549 // PointersArray and SizesArray. The original variables for these arrays are
4550 // not captured and we get their addresses explicitly.
4551 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004552 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004553 SrcBase = CGF.MakeAddrLValue(
4554 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4555 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4556 SharedsTy);
4557 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004558 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004559 for (const PrivateDataTy &Pair : Privates) {
4560 const VarDecl *VD = Pair.second.PrivateCopy;
4561 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004562 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4563 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004564 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004565 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4566 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004567 // Check if the variable is the target-based BasePointersArray,
4568 // PointersArray or SizesArray.
4569 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004570 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004571 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004572 if (IsTargetTask && !SharedField) {
4573 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4574 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4575 cast<CapturedDecl>(OriginalVD->getDeclContext())
4576 ->getNumParams() == 0 &&
4577 isa<TranslationUnitDecl>(
4578 cast<CapturedDecl>(OriginalVD->getDeclContext())
4579 ->getDeclContext()) &&
4580 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004581 SharedRefLValue =
4582 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4583 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004584 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4585 SharedRefLValue = CGF.MakeAddrLValue(
4586 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4587 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4588 SharedRefLValue.getTBAAInfo());
4589 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004590 if (Type->isArrayType()) {
4591 // Initialize firstprivate array.
4592 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4593 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004594 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004595 } else {
4596 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004597 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004598 CGF.EmitOMPAggregateAssign(
4599 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4600 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4601 Address SrcElement) {
4602 // Clean up any temporaries needed by the initialization.
4603 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4604 InitScope.addPrivate(
4605 Elem, [SrcElement]() -> Address { return SrcElement; });
4606 (void)InitScope.Privatize();
4607 // Emit initialization for single element.
4608 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4609 CGF, &CapturesInfo);
4610 CGF.EmitAnyExprToMem(Init, DestElement,
4611 Init->getType().getQualifiers(),
4612 /*IsInitializer=*/false);
4613 });
4614 }
4615 } else {
4616 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4617 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4618 return SharedRefLValue.getAddress();
4619 });
4620 (void)InitScope.Privatize();
4621 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4622 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4623 /*capturedByInit=*/false);
4624 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004625 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004626 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004627 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004628 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004629 ++FI;
4630 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004631}
4632
4633/// Check if duplication function is required for taskloops.
4634static bool checkInitIsRequired(CodeGenFunction &CGF,
4635 ArrayRef<PrivateDataTy> Privates) {
4636 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004637 for (const PrivateDataTy &Pair : Privates) {
4638 const VarDecl *VD = Pair.second.PrivateCopy;
4639 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004640 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4641 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004642 if (InitRequired)
4643 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004644 }
4645 return InitRequired;
4646}
4647
4648
4649/// Emit task_dup function (for initialization of
4650/// private/firstprivate/lastprivate vars and last_iter flag)
4651/// \code
4652/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4653/// lastpriv) {
4654/// // setup lastprivate flag
4655/// task_dst->last = lastpriv;
4656/// // could be constructor calls here...
4657/// }
4658/// \endcode
4659static llvm::Value *
4660emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4661 const OMPExecutableDirective &D,
4662 QualType KmpTaskTWithPrivatesPtrQTy,
4663 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4664 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4665 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4666 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004667 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004668 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004669 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4670 KmpTaskTWithPrivatesPtrQTy,
4671 ImplicitParamDecl::Other);
4672 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4673 KmpTaskTWithPrivatesPtrQTy,
4674 ImplicitParamDecl::Other);
4675 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4676 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004677 Args.push_back(&DstArg);
4678 Args.push_back(&SrcArg);
4679 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004680 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004681 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004682 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004683 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4684 auto *TaskDup = llvm::Function::Create(
4685 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004686 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004687 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004688 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004689 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4690 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004691
4692 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4693 CGF.GetAddrOfLocalVar(&DstArg),
4694 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4695 // task_dst->liter = lastpriv;
4696 if (WithLastIter) {
4697 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4698 LValue Base = CGF.EmitLValueForField(
4699 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4700 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4701 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4702 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4703 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4704 }
4705
4706 // Emit initial values for private copies (if any).
4707 assert(!Privates.empty());
4708 Address KmpTaskSharedsPtr = Address::invalid();
4709 if (!Data.FirstprivateVars.empty()) {
4710 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4711 CGF.GetAddrOfLocalVar(&SrcArg),
4712 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4713 LValue Base = CGF.EmitLValueForField(
4714 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4715 KmpTaskSharedsPtr = Address(
4716 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4717 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4718 KmpTaskTShareds)),
4719 Loc),
4720 CGF.getNaturalTypeAlignment(SharedsTy));
4721 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004722 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4723 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004724 CGF.FinishFunction();
4725 return TaskDup;
4726}
4727
Alexey Bataev8a831592016-05-10 10:36:51 +00004728/// Checks if destructor function is required to be generated.
4729/// \return true if cleanups are required, false otherwise.
4730static bool
4731checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4732 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004733 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4734 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4735 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004736 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4737 if (NeedsCleanup)
4738 break;
4739 }
4740 return NeedsCleanup;
4741}
4742
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004743CGOpenMPRuntime::TaskResultTy
4744CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4745 const OMPExecutableDirective &D,
4746 llvm::Value *TaskFunction, QualType SharedsTy,
4747 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004748 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004749 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004750 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004751 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004752 for (const Expr *E : Data.PrivateVars) {
4753 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004754 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004755 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004756 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004757 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004758 ++I;
4759 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004760 I = Data.FirstprivateCopies.begin();
4761 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004762 for (const Expr *E : Data.FirstprivateVars) {
4763 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004764 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004765 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004766 PrivateHelpersTy(
4767 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004768 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004769 ++I;
4770 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004771 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004772 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004773 for (const Expr *E : Data.LastprivateVars) {
4774 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004775 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004776 C.getDeclAlign(VD),
4777 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004778 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004779 ++I;
4780 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004781 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004782 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004783 // Build type kmp_routine_entry_t (if not built yet).
4784 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004785 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004786 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4787 if (SavedKmpTaskloopTQTy.isNull()) {
4788 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4789 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4790 }
4791 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004792 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004793 assert((D.getDirectiveKind() == OMPD_task ||
4794 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4795 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4796 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004797 if (SavedKmpTaskTQTy.isNull()) {
4798 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4799 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4800 }
4801 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004802 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004803 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004804 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004805 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004806 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004807 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004808 QualType KmpTaskTWithPrivatesPtrQTy =
4809 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004810 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4811 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4812 KmpTaskTWithPrivatesTy->getPointerTo();
4813 llvm::Value *KmpTaskTWithPrivatesTySize =
4814 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004815 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4816
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004817 // Emit initial values for private copies (if any).
4818 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004819 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004820 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004821 if (!Privates.empty()) {
4822 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004823 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4824 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4825 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004826 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4827 TaskPrivatesMap, TaskPrivatesMapTy);
4828 } else {
4829 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4830 cast<llvm::PointerType>(TaskPrivatesMapTy));
4831 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004832 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4833 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004834 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004835 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4836 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4837 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004838
4839 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4840 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4841 // kmp_routine_entry_t *task_entry);
4842 // Task flags. Format is taken from
4843 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4844 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004845 enum {
4846 TiedFlag = 0x1,
4847 FinalFlag = 0x2,
4848 DestructorsFlag = 0x8,
4849 PriorityFlag = 0x20
4850 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004851 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004852 bool NeedsCleanup = false;
4853 if (!Privates.empty()) {
4854 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4855 if (NeedsCleanup)
4856 Flags = Flags | DestructorsFlag;
4857 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004858 if (Data.Priority.getInt())
4859 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004860 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004861 Data.Final.getPointer()
4862 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004863 CGF.Builder.getInt32(FinalFlag),
4864 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004865 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004866 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004867 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004868 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4869 getThreadID(CGF, Loc), TaskFlags,
4870 KmpTaskTWithPrivatesTySize, SharedsSize,
4871 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4872 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004873 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004874 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004875 llvm::Value *NewTaskNewTaskTTy =
4876 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4877 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004878 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4879 KmpTaskTWithPrivatesQTy);
4880 LValue TDBase =
4881 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004882 // Fill the data in the resulting kmp_task_t record.
4883 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004884 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004885 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004886 KmpTaskSharedsPtr =
4887 Address(CGF.EmitLoadOfScalar(
4888 CGF.EmitLValueForField(
4889 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4890 KmpTaskTShareds)),
4891 Loc),
4892 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004893 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4894 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004895 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004896 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004897 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004898 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004899 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004900 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4901 SharedsTy, SharedsPtrTy, Data, Privates,
4902 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004903 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4904 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4905 Result.TaskDupFn = emitTaskDupFunction(
4906 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4907 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4908 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004909 }
4910 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004911 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4912 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004913 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004914 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004915 const RecordDecl *KmpCmplrdataUD =
4916 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004917 if (NeedsCleanup) {
4918 llvm::Value *DestructorFn = emitDestructorsFunction(
4919 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4920 KmpTaskTWithPrivatesQTy);
4921 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4922 LValue DestructorsLV = CGF.EmitLValueForField(
4923 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4924 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4925 DestructorFn, KmpRoutineEntryPtrTy),
4926 DestructorsLV);
4927 }
4928 // Set priority.
4929 if (Data.Priority.getInt()) {
4930 LValue Data2LV = CGF.EmitLValueForField(
4931 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4932 LValue PriorityLV = CGF.EmitLValueForField(
4933 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4934 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4935 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004936 Result.NewTask = NewTask;
4937 Result.TaskEntry = TaskEntry;
4938 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4939 Result.TDBase = TDBase;
4940 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4941 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004942}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004943
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004944void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4945 const OMPExecutableDirective &D,
4946 llvm::Value *TaskFunction,
4947 QualType SharedsTy, Address Shareds,
4948 const Expr *IfCond,
4949 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004950 if (!CGF.HaveInsertPoint())
4951 return;
4952
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004953 TaskResultTy Result =
4954 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4955 llvm::Value *NewTask = Result.NewTask;
4956 llvm::Value *TaskEntry = Result.TaskEntry;
4957 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4958 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004959 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4960 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004961 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004962 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004963 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004964 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004965 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004966 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004967 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4968 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004969 QualType FlagsTy =
4970 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004971 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4972 if (KmpDependInfoTy.isNull()) {
4973 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4974 KmpDependInfoRD->startDefinition();
4975 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4976 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4977 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4978 KmpDependInfoRD->completeDefinition();
4979 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004980 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004981 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004982 }
John McCall7f416cc2015-09-08 08:05:57 +00004983 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004984 // Define type kmp_depend_info[<Dependences.size()>];
4985 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004986 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004987 ArrayType::Normal, /*IndexTypeQuals=*/0);
4988 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004989 DependenciesArray =
4990 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004991 for (unsigned I = 0; I < NumDependencies; ++I) {
4992 const Expr *E = Data.Dependences[I].second;
4993 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004994 llvm::Value *Size;
4995 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004996 if (const auto *ASE =
4997 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004998 LValue UpAddrLVal =
4999 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5000 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005001 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005002 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005003 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005004 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5005 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005006 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005007 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005008 }
5009 LValue Base = CGF.MakeAddrLValue(
5010 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005011 KmpDependInfoTy);
5012 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005013 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005014 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005015 CGF.EmitStoreOfScalar(
5016 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5017 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005018 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005019 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005020 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5021 CGF.EmitStoreOfScalar(Size, LenLVal);
5022 // deps[i].flags = <Dependences[i].first>;
5023 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005024 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005025 case OMPC_DEPEND_in:
5026 DepKind = DepIn;
5027 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005028 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005029 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005030 case OMPC_DEPEND_inout:
5031 DepKind = DepInOut;
5032 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005033 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005034 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005035 case OMPC_DEPEND_unknown:
5036 llvm_unreachable("Unknown task dependence type");
5037 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005038 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005039 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5040 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5041 FlagsLVal);
5042 }
John McCall7f416cc2015-09-08 08:05:57 +00005043 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5044 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005045 CGF.VoidPtrTy);
5046 }
5047
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005048 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005049 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005050 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5051 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5052 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5053 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005054 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5055 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005056 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5057 llvm::Value *DepTaskArgs[7];
5058 if (NumDependencies) {
5059 DepTaskArgs[0] = UpLoc;
5060 DepTaskArgs[1] = ThreadID;
5061 DepTaskArgs[2] = NewTask;
5062 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5063 DepTaskArgs[4] = DependenciesArray.getPointer();
5064 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5065 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5066 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005067 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5068 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005069 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005070 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005071 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005072 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005073 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5074 }
John McCall7f416cc2015-09-08 08:05:57 +00005075 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005076 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005077 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005078 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005079 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005080 TaskArgs);
5081 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005082 // Check if parent region is untied and build return for untied task;
5083 if (auto *Region =
5084 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5085 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005086 };
John McCall7f416cc2015-09-08 08:05:57 +00005087
5088 llvm::Value *DepWaitTaskArgs[6];
5089 if (NumDependencies) {
5090 DepWaitTaskArgs[0] = UpLoc;
5091 DepWaitTaskArgs[1] = ThreadID;
5092 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5093 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5094 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5095 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5096 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005097 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005098 NumDependencies, &DepWaitTaskArgs,
5099 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005100 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005101 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5102 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5103 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5104 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5105 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005106 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005107 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005108 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005109 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005110 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5111 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005112 Action.Enter(CGF);
5113 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005114 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005115 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005116 };
5117
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005118 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5119 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005120 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5121 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005122 RegionCodeGenTy RCG(CodeGen);
5123 CommonActionTy Action(
5124 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5125 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5126 RCG.setAction(Action);
5127 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005128 };
John McCall7f416cc2015-09-08 08:05:57 +00005129
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005130 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005131 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005132 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005133 RegionCodeGenTy ThenRCG(ThenCodeGen);
5134 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005135 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005136}
5137
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005138void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5139 const OMPLoopDirective &D,
5140 llvm::Value *TaskFunction,
5141 QualType SharedsTy, Address Shareds,
5142 const Expr *IfCond,
5143 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005144 if (!CGF.HaveInsertPoint())
5145 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005146 TaskResultTy Result =
5147 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005148 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005149 // libcall.
5150 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5151 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5152 // sched, kmp_uint64 grainsize, void *task_dup);
5153 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5154 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5155 llvm::Value *IfVal;
5156 if (IfCond) {
5157 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5158 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005159 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005160 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005161 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005162
5163 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005164 Result.TDBase,
5165 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005166 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005167 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5168 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5169 /*IsInitializer=*/true);
5170 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005171 Result.TDBase,
5172 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005173 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005174 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5175 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5176 /*IsInitializer=*/true);
5177 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005178 Result.TDBase,
5179 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005180 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005181 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5182 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5183 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005184 // Store reductions address.
5185 LValue RedLVal = CGF.EmitLValueForField(
5186 Result.TDBase,
5187 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005188 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005189 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005190 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005191 CGF.EmitNullInitialization(RedLVal.getAddress(),
5192 CGF.getContext().VoidPtrTy);
5193 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005194 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005195 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005196 UpLoc,
5197 ThreadID,
5198 Result.NewTask,
5199 IfVal,
5200 LBLVal.getPointer(),
5201 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005202 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00005203 llvm::ConstantInt::getNullValue(
5204 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005205 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005206 CGF.IntTy, Data.Schedule.getPointer()
5207 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005208 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005209 Data.Schedule.getPointer()
5210 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005211 /*isSigned=*/false)
5212 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005213 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5214 Result.TaskDupFn, CGF.VoidPtrTy)
5215 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005216 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5217}
5218
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005219/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005220/// array sections) LHS op = RHS.
5221/// \param Type Type of array.
5222/// \param LHSVar Variable on the left side of the reduction operation
5223/// (references element of array in original variable).
5224/// \param RHSVar Variable on the right side of the reduction operation
5225/// (references element of array in original variable).
5226/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5227/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005228static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005229 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5230 const VarDecl *RHSVar,
5231 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5232 const Expr *, const Expr *)> &RedOpGen,
5233 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5234 const Expr *UpExpr = nullptr) {
5235 // Perform element-by-element initialization.
5236 QualType ElementTy;
5237 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5238 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5239
5240 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005241 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5242 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005243
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005244 llvm::Value *RHSBegin = RHSAddr.getPointer();
5245 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005246 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005247 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005248 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005249 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5250 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5251 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005252 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5253 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5254
5255 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005256 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005257 CGF.EmitBlock(BodyBB);
5258
5259 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5260
5261 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5262 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5263 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5264 Address RHSElementCurrent =
5265 Address(RHSElementPHI,
5266 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5267
5268 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5269 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5270 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5271 Address LHSElementCurrent =
5272 Address(LHSElementPHI,
5273 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5274
5275 // Emit copy.
5276 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005277 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5278 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005279 Scope.Privatize();
5280 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5281 Scope.ForceCleanup();
5282
5283 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005284 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005285 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005286 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005287 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5288 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005289 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005290 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5291 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5292 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5293 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5294
5295 // Done.
5296 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5297}
5298
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005299/// Emit reduction combiner. If the combiner is a simple expression emit it as
5300/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5301/// UDR combiner function.
5302static void emitReductionCombiner(CodeGenFunction &CGF,
5303 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005304 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5305 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5306 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005307 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005308 if (const auto *DRD =
5309 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005310 std::pair<llvm::Function *, llvm::Function *> Reduction =
5311 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5312 RValue Func = RValue::get(Reduction.first);
5313 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5314 CGF.EmitIgnoredExpr(ReductionOp);
5315 return;
5316 }
5317 CGF.EmitIgnoredExpr(ReductionOp);
5318}
5319
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005320llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005321 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5322 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5323 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005324 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005325
5326 // void reduction_func(void *LHSArg, void *RHSArg);
5327 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005328 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5329 ImplicitParamDecl::Other);
5330 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5331 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005332 Args.push_back(&LHSArg);
5333 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005334 const auto &CGFI =
5335 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005336 std::string Name = getName({"omp", "reduction", "reduction_func"});
5337 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5338 llvm::GlobalValue::InternalLinkage, Name,
5339 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005340 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005341 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005342 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005343 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005344
5345 // Dst = (void*[n])(LHSArg);
5346 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005347 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5348 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5349 ArgsType), CGF.getPointerAlign());
5350 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5351 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5352 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005353
5354 // ...
5355 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5356 // ...
5357 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005358 auto IPriv = Privates.begin();
5359 unsigned Idx = 0;
5360 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005361 const auto *RHSVar =
5362 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5363 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005364 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005365 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005366 const auto *LHSVar =
5367 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5368 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005369 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005370 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005371 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005372 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005373 // Get array size and emit VLA type.
5374 ++Idx;
5375 Address Elem =
5376 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5377 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005378 const VariableArrayType *VLA =
5379 CGF.getContext().getAsVariableArrayType(PrivTy);
5380 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005381 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005382 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005383 CGF.EmitVariablyModifiedType(PrivTy);
5384 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005385 }
5386 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005387 IPriv = Privates.begin();
5388 auto ILHS = LHSExprs.begin();
5389 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005390 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005391 if ((*IPriv)->getType()->isArrayType()) {
5392 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005393 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5394 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005395 EmitOMPAggregateReduction(
5396 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5397 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5398 emitReductionCombiner(CGF, E);
5399 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005400 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005401 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005402 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005403 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005404 ++IPriv;
5405 ++ILHS;
5406 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005407 }
5408 Scope.ForceCleanup();
5409 CGF.FinishFunction();
5410 return Fn;
5411}
5412
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005413void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5414 const Expr *ReductionOp,
5415 const Expr *PrivateRef,
5416 const DeclRefExpr *LHS,
5417 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005418 if (PrivateRef->getType()->isArrayType()) {
5419 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005420 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5421 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005422 EmitOMPAggregateReduction(
5423 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5424 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5425 emitReductionCombiner(CGF, ReductionOp);
5426 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005427 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005428 // Emit reduction for array subscript or single variable.
5429 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005430 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005431}
5432
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005433void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005434 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005435 ArrayRef<const Expr *> LHSExprs,
5436 ArrayRef<const Expr *> RHSExprs,
5437 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005438 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005439 if (!CGF.HaveInsertPoint())
5440 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005441
5442 bool WithNowait = Options.WithNowait;
5443 bool SimpleReduction = Options.SimpleReduction;
5444
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005445 // Next code should be emitted for reduction:
5446 //
5447 // static kmp_critical_name lock = { 0 };
5448 //
5449 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5450 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5451 // ...
5452 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5453 // *(Type<n>-1*)rhs[<n>-1]);
5454 // }
5455 //
5456 // ...
5457 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5458 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5459 // RedList, reduce_func, &<lock>)) {
5460 // case 1:
5461 // ...
5462 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5463 // ...
5464 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5465 // break;
5466 // case 2:
5467 // ...
5468 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5469 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005470 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005471 // break;
5472 // default:;
5473 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005474 //
5475 // if SimpleReduction is true, only the next code is generated:
5476 // ...
5477 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5478 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005479
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005480 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005481
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005482 if (SimpleReduction) {
5483 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005484 auto IPriv = Privates.begin();
5485 auto ILHS = LHSExprs.begin();
5486 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005487 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005488 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5489 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005490 ++IPriv;
5491 ++ILHS;
5492 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005493 }
5494 return;
5495 }
5496
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005497 // 1. Build a list of reduction variables.
5498 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005499 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005500 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005501 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005502 // Reserve place for array size.
5503 ++Size;
5504 }
5505 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005506 QualType ReductionArrayTy =
5507 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5508 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005509 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005510 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005511 auto IPriv = Privates.begin();
5512 unsigned Idx = 0;
5513 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005514 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005515 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005516 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005517 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005518 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5519 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005520 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005521 // Store array size.
5522 ++Idx;
5523 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5524 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005525 llvm::Value *Size = CGF.Builder.CreateIntCast(
5526 CGF.getVLASize(
5527 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005528 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005529 CGF.SizeTy, /*isSigned=*/false);
5530 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5531 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005532 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005533 }
5534
5535 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005536 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005537 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5538 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005539
5540 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005541 std::string Name = getName({"reduction"});
5542 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005543
5544 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5545 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005546 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5547 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5548 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5549 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005550 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005551 llvm::Value *Args[] = {
5552 IdentTLoc, // ident_t *<loc>
5553 ThreadId, // i32 <gtid>
5554 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5555 ReductionArrayTySize, // size_type sizeof(RedList)
5556 RL, // void *RedList
5557 ReductionFn, // void (*) (void *, void *) <reduce_func>
5558 Lock // kmp_critical_name *&<lock>
5559 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005560 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005561 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5562 : OMPRTL__kmpc_reduce),
5563 Args);
5564
5565 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005566 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5567 llvm::SwitchInst *SwInst =
5568 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005569
5570 // 6. Build case 1:
5571 // ...
5572 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5573 // ...
5574 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5575 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005576 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005577 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5578 CGF.EmitBlock(Case1BB);
5579
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005580 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5581 llvm::Value *EndArgs[] = {
5582 IdentTLoc, // ident_t *<loc>
5583 ThreadId, // i32 <gtid>
5584 Lock // kmp_critical_name *&<lock>
5585 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005586 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5587 CodeGenFunction &CGF, PrePostActionTy &Action) {
5588 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005589 auto IPriv = Privates.begin();
5590 auto ILHS = LHSExprs.begin();
5591 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005592 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005593 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5594 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005595 ++IPriv;
5596 ++ILHS;
5597 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005598 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005599 };
5600 RegionCodeGenTy RCG(CodeGen);
5601 CommonActionTy Action(
5602 nullptr, llvm::None,
5603 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5604 : OMPRTL__kmpc_end_reduce),
5605 EndArgs);
5606 RCG.setAction(Action);
5607 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005608
5609 CGF.EmitBranch(DefaultBB);
5610
5611 // 7. Build case 2:
5612 // ...
5613 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5614 // ...
5615 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005616 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005617 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5618 CGF.EmitBlock(Case2BB);
5619
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005620 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5621 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005622 auto ILHS = LHSExprs.begin();
5623 auto IRHS = RHSExprs.begin();
5624 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005625 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005626 const Expr *XExpr = nullptr;
5627 const Expr *EExpr = nullptr;
5628 const Expr *UpExpr = nullptr;
5629 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005630 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005631 if (BO->getOpcode() == BO_Assign) {
5632 XExpr = BO->getLHS();
5633 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005634 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005635 }
5636 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005637 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005638 if (RHSExpr) {
5639 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005640 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005641 RHSExpr->IgnoreParenImpCasts())) {
5642 // If this is a conditional operator, analyze its condition for
5643 // min/max reduction operator.
5644 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005645 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005646 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005647 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5648 EExpr = BORHS->getRHS();
5649 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005650 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005651 }
5652 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005653 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005654 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005655 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5656 const Expr *EExpr, const Expr *UpExpr) {
5657 LValue X = CGF.EmitLValue(XExpr);
5658 RValue E;
5659 if (EExpr)
5660 E = CGF.EmitAnyExpr(EExpr);
5661 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005662 X, E, BO, /*IsXLHSInRHSPart=*/true,
5663 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005664 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005665 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5666 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005667 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005668 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5669 CGF.emitOMPSimpleStore(
5670 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5671 VD->getType().getNonReferenceType(), Loc);
5672 return LHSTemp;
5673 });
5674 (void)PrivateScope.Privatize();
5675 return CGF.EmitAnyExpr(UpExpr);
5676 });
5677 };
5678 if ((*IPriv)->getType()->isArrayType()) {
5679 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005680 const auto *RHSVar =
5681 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005682 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5683 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005684 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005685 // Emit atomic reduction for array subscript or single variable.
5686 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005687 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005688 } else {
5689 // Emit as a critical region.
5690 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005691 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005692 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005693 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005694 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005695 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005696 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5697 Action.Enter(CGF);
5698 emitReductionCombiner(CGF, E);
5699 },
5700 Loc);
5701 };
5702 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005703 const auto *LHSVar =
5704 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5705 const auto *RHSVar =
5706 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005707 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5708 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005709 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005710 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005711 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005712 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005713 ++ILHS;
5714 ++IRHS;
5715 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005716 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005717 };
5718 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5719 if (!WithNowait) {
5720 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5721 llvm::Value *EndArgs[] = {
5722 IdentTLoc, // ident_t *<loc>
5723 ThreadId, // i32 <gtid>
5724 Lock // kmp_critical_name *&<lock>
5725 };
5726 CommonActionTy Action(nullptr, llvm::None,
5727 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5728 EndArgs);
5729 AtomicRCG.setAction(Action);
5730 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005731 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005732 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005733 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005734
5735 CGF.EmitBranch(DefaultBB);
5736 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5737}
5738
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005739/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005740/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5741static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5742 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005743 SmallString<256> Buffer;
5744 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005745 const clang::DeclRefExpr *DE;
5746 const VarDecl *D = ::getBaseDecl(Ref, DE);
5747 if (!D)
5748 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5749 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005750 std::string Name = CGM.getOpenMPRuntime().getName(
5751 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5752 Out << Prefix << Name << "_"
5753 << D->getCanonicalDecl()->getLocStart().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005754 return Out.str();
5755}
5756
5757/// Emits reduction initializer function:
5758/// \code
5759/// void @.red_init(void* %arg) {
5760/// %0 = bitcast void* %arg to <type>*
5761/// store <type> <init>, <type>* %0
5762/// ret void
5763/// }
5764/// \endcode
5765static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5766 SourceLocation Loc,
5767 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005768 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005769 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005770 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5771 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005772 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005773 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005774 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005775 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005776 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005777 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005778 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005779 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005780 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005781 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005782 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005783 Address PrivateAddr = CGF.EmitLoadOfPointer(
5784 CGF.GetAddrOfLocalVar(&Param),
5785 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5786 llvm::Value *Size = nullptr;
5787 // If the size of the reduction item is non-constant, load it from global
5788 // threadprivate variable.
5789 if (RCG.getSizes(N).second) {
5790 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5791 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005792 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005793 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5794 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005795 }
5796 RCG.emitAggregateType(CGF, N, Size);
5797 LValue SharedLVal;
5798 // If initializer uses initializer from declare reduction construct, emit a
5799 // pointer to the address of the original reduction item (reuired by reduction
5800 // initializer)
5801 if (RCG.usesReductionInitializer(N)) {
5802 Address SharedAddr =
5803 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5804 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005805 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005806 SharedAddr = CGF.EmitLoadOfPointer(
5807 SharedAddr,
5808 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005809 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5810 } else {
5811 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5812 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5813 CGM.getContext().VoidPtrTy);
5814 }
5815 // Emit the initializer:
5816 // %0 = bitcast void* %arg to <type>*
5817 // store <type> <init>, <type>* %0
5818 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5819 [](CodeGenFunction &) { return false; });
5820 CGF.FinishFunction();
5821 return Fn;
5822}
5823
5824/// Emits reduction combiner function:
5825/// \code
5826/// void @.red_comb(void* %arg0, void* %arg1) {
5827/// %lhs = bitcast void* %arg0 to <type>*
5828/// %rhs = bitcast void* %arg1 to <type>*
5829/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5830/// store <type> %2, <type>* %lhs
5831/// ret void
5832/// }
5833/// \endcode
5834static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5835 SourceLocation Loc,
5836 ReductionCodeGen &RCG, unsigned N,
5837 const Expr *ReductionOp,
5838 const Expr *LHS, const Expr *RHS,
5839 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005840 ASTContext &C = CGM.getContext();
5841 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5842 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005843 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005844 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5845 C.VoidPtrTy, ImplicitParamDecl::Other);
5846 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5847 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005848 Args.emplace_back(&ParamInOut);
5849 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005850 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005851 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005852 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005853 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005854 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005855 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005856 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005857 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005858 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005859 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005860 llvm::Value *Size = nullptr;
5861 // If the size of the reduction item is non-constant, load it from global
5862 // threadprivate variable.
5863 if (RCG.getSizes(N).second) {
5864 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5865 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005866 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005867 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5868 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005869 }
5870 RCG.emitAggregateType(CGF, N, Size);
5871 // Remap lhs and rhs variables to the addresses of the function arguments.
5872 // %lhs = bitcast void* %arg0 to <type>*
5873 // %rhs = bitcast void* %arg1 to <type>*
5874 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005875 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005876 // Pull out the pointer to the variable.
5877 Address PtrAddr = CGF.EmitLoadOfPointer(
5878 CGF.GetAddrOfLocalVar(&ParamInOut),
5879 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5880 return CGF.Builder.CreateElementBitCast(
5881 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5882 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005883 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005884 // Pull out the pointer to the variable.
5885 Address PtrAddr = CGF.EmitLoadOfPointer(
5886 CGF.GetAddrOfLocalVar(&ParamIn),
5887 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5888 return CGF.Builder.CreateElementBitCast(
5889 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5890 });
5891 PrivateScope.Privatize();
5892 // Emit the combiner body:
5893 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5894 // store <type> %2, <type>* %lhs
5895 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5896 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5897 cast<DeclRefExpr>(RHS));
5898 CGF.FinishFunction();
5899 return Fn;
5900}
5901
5902/// Emits reduction finalizer function:
5903/// \code
5904/// void @.red_fini(void* %arg) {
5905/// %0 = bitcast void* %arg to <type>*
5906/// <destroy>(<type>* %0)
5907/// ret void
5908/// }
5909/// \endcode
5910static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5911 SourceLocation Loc,
5912 ReductionCodeGen &RCG, unsigned N) {
5913 if (!RCG.needCleanups(N))
5914 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005915 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005916 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005917 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5918 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005919 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005920 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005921 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005922 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005923 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005924 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005925 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005926 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005927 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005928 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005929 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005930 Address PrivateAddr = CGF.EmitLoadOfPointer(
5931 CGF.GetAddrOfLocalVar(&Param),
5932 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5933 llvm::Value *Size = nullptr;
5934 // If the size of the reduction item is non-constant, load it from global
5935 // threadprivate variable.
5936 if (RCG.getSizes(N).second) {
5937 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5938 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005939 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005940 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5941 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005942 }
5943 RCG.emitAggregateType(CGF, N, Size);
5944 // Emit the finalizer body:
5945 // <destroy>(<type>* %0)
5946 RCG.emitCleanups(CGF, N, PrivateAddr);
5947 CGF.FinishFunction();
5948 return Fn;
5949}
5950
5951llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5952 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5953 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5954 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5955 return nullptr;
5956
5957 // Build typedef struct:
5958 // kmp_task_red_input {
5959 // void *reduce_shar; // shared reduction item
5960 // size_t reduce_size; // size of data item
5961 // void *reduce_init; // data initialization routine
5962 // void *reduce_fini; // data finalization routine
5963 // void *reduce_comb; // data combiner routine
5964 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5965 // } kmp_task_red_input_t;
5966 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005967 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005968 RD->startDefinition();
5969 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5970 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5971 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5972 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5973 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5974 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5975 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5976 RD->completeDefinition();
5977 QualType RDType = C.getRecordType(RD);
5978 unsigned Size = Data.ReductionVars.size();
5979 llvm::APInt ArraySize(/*numBits=*/64, Size);
5980 QualType ArrayRDType = C.getConstantArrayType(
5981 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5982 // kmp_task_red_input_t .rd_input.[Size];
5983 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5984 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5985 Data.ReductionOps);
5986 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5987 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5988 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5989 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5990 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5991 TaskRedInput.getPointer(), Idxs,
5992 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5993 ".rd_input.gep.");
5994 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5995 // ElemLVal.reduce_shar = &Shareds[Cnt];
5996 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5997 RCG.emitSharedLValue(CGF, Cnt);
5998 llvm::Value *CastedShared =
5999 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6000 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6001 RCG.emitAggregateType(CGF, Cnt);
6002 llvm::Value *SizeValInChars;
6003 llvm::Value *SizeVal;
6004 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6005 // We use delayed creation/initialization for VLAs, array sections and
6006 // custom reduction initializations. It is required because runtime does not
6007 // provide the way to pass the sizes of VLAs/array sections to
6008 // initializer/combiner/finalizer functions and does not pass the pointer to
6009 // original reduction item to the initializer. Instead threadprivate global
6010 // variables are used to store these values and use them in the functions.
6011 bool DelayedCreation = !!SizeVal;
6012 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6013 /*isSigned=*/false);
6014 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6015 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6016 // ElemLVal.reduce_init = init;
6017 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6018 llvm::Value *InitAddr =
6019 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6020 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6021 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6022 // ElemLVal.reduce_fini = fini;
6023 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6024 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6025 llvm::Value *FiniAddr = Fini
6026 ? CGF.EmitCastToVoidPtr(Fini)
6027 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6028 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6029 // ElemLVal.reduce_comb = comb;
6030 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6031 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6032 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6033 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6034 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6035 // ElemLVal.flags = 0;
6036 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6037 if (DelayedCreation) {
6038 CGF.EmitStoreOfScalar(
6039 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6040 FlagsLVal);
6041 } else
6042 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6043 }
6044 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6045 // *data);
6046 llvm::Value *Args[] = {
6047 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6048 /*isSigned=*/true),
6049 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6050 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6051 CGM.VoidPtrTy)};
6052 return CGF.EmitRuntimeCall(
6053 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6054}
6055
6056void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6057 SourceLocation Loc,
6058 ReductionCodeGen &RCG,
6059 unsigned N) {
6060 auto Sizes = RCG.getSizes(N);
6061 // Emit threadprivate global variable if the type is non-constant
6062 // (Sizes.second = nullptr).
6063 if (Sizes.second) {
6064 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6065 /*isSigned=*/false);
6066 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6067 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006068 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006069 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6070 }
6071 // Store address of the original reduction item if custom initializer is used.
6072 if (RCG.usesReductionInitializer(N)) {
6073 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6074 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006075 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006076 CGF.Builder.CreateStore(
6077 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6078 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6079 SharedAddr, /*IsVolatile=*/false);
6080 }
6081}
6082
6083Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6084 SourceLocation Loc,
6085 llvm::Value *ReductionsPtr,
6086 LValue SharedLVal) {
6087 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6088 // *d);
6089 llvm::Value *Args[] = {
6090 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6091 /*isSigned=*/true),
6092 ReductionsPtr,
6093 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6094 CGM.VoidPtrTy)};
6095 return Address(
6096 CGF.EmitRuntimeCall(
6097 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6098 SharedLVal.getAlignment());
6099}
6100
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006101void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6102 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006103 if (!CGF.HaveInsertPoint())
6104 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006105 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6106 // global_tid);
6107 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6108 // Ignore return result until untied tasks are supported.
6109 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006110 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6111 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006112}
6113
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006114void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006115 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006116 const RegionCodeGenTy &CodeGen,
6117 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006118 if (!CGF.HaveInsertPoint())
6119 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006120 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006121 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006122}
6123
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006124namespace {
6125enum RTCancelKind {
6126 CancelNoreq = 0,
6127 CancelParallel = 1,
6128 CancelLoop = 2,
6129 CancelSections = 3,
6130 CancelTaskgroup = 4
6131};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006132} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006133
6134static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6135 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006136 if (CancelRegion == OMPD_parallel)
6137 CancelKind = CancelParallel;
6138 else if (CancelRegion == OMPD_for)
6139 CancelKind = CancelLoop;
6140 else if (CancelRegion == OMPD_sections)
6141 CancelKind = CancelSections;
6142 else {
6143 assert(CancelRegion == OMPD_taskgroup);
6144 CancelKind = CancelTaskgroup;
6145 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006146 return CancelKind;
6147}
6148
6149void CGOpenMPRuntime::emitCancellationPointCall(
6150 CodeGenFunction &CGF, SourceLocation Loc,
6151 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006152 if (!CGF.HaveInsertPoint())
6153 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006154 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6155 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006156 if (auto *OMPRegionInfo =
6157 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006158 // For 'cancellation point taskgroup', the task region info may not have a
6159 // cancel. This may instead happen in another adjacent task.
6160 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006161 llvm::Value *Args[] = {
6162 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6163 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006164 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006165 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006166 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6167 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006168 // exit from construct;
6169 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006170 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6171 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6172 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006173 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6174 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006175 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006176 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006177 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006178 CGF.EmitBranchThroughCleanup(CancelDest);
6179 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6180 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006181 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006182}
6183
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006184void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006185 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006186 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006187 if (!CGF.HaveInsertPoint())
6188 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006189 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6190 // kmp_int32 cncl_kind);
6191 if (auto *OMPRegionInfo =
6192 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006193 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6194 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006195 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006196 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006197 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006198 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6199 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006200 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006201 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006202 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006203 // exit from construct;
6204 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006205 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6206 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6207 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006208 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6209 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006210 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006211 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006212 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6213 CGF.EmitBranchThroughCleanup(CancelDest);
6214 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6215 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006216 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006217 emitOMPIfClause(CGF, IfCond, ThenGen,
6218 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006219 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006220 RegionCodeGenTy ThenRCG(ThenGen);
6221 ThenRCG(CGF);
6222 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006223 }
6224}
Samuel Antaobed3c462015-10-02 16:14:20 +00006225
Samuel Antaoee8fb302016-01-06 13:42:12 +00006226void CGOpenMPRuntime::emitTargetOutlinedFunction(
6227 const OMPExecutableDirective &D, StringRef ParentName,
6228 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006229 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006230 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006231 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6232 IsOffloadEntry, CodeGen);
6233}
6234
6235void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6236 const OMPExecutableDirective &D, StringRef ParentName,
6237 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6238 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006239 // Create a unique name for the entry function using the source location
6240 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006241 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006242 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006243 //
6244 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006245 // mangled name of the function that encloses the target region and BB is the
6246 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006247
6248 unsigned DeviceID;
6249 unsigned FileID;
6250 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006251 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006252 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006253 SmallString<64> EntryFnName;
6254 {
6255 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006256 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6257 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006258 }
6259
Alexey Bataev475a7442018-01-12 19:39:11 +00006260 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006261
Samuel Antaobed3c462015-10-02 16:14:20 +00006262 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006263 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006264 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006265
Samuel Antao6d004262016-06-16 18:39:34 +00006266 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006267
6268 // If this target outline function is not an offload entry, we don't need to
6269 // register it.
6270 if (!IsOffloadEntry)
6271 return;
6272
6273 // The target region ID is used by the runtime library to identify the current
6274 // target region, so it only has to be unique and not necessarily point to
6275 // anything. It could be the pointer to the outlined function that implements
6276 // the target region, but we aren't using that so that the compiler doesn't
6277 // need to keep that, and could therefore inline the host function if proven
6278 // worthwhile during optimization. In the other hand, if emitting code for the
6279 // device, the ID has to be the function address so that it can retrieved from
6280 // the offloading entry and launched by the runtime library. We also mark the
6281 // outlined function to have external linkage in case we are emitting code for
6282 // the device, because these functions will be entry points to the device.
6283
6284 if (CGM.getLangOpts().OpenMPIsDevice) {
6285 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006286 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006287 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006288 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006289 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006290 OutlinedFnID = new llvm::GlobalVariable(
6291 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006292 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006293 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006294 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006295
6296 // Register the information for the entry associated with this target region.
6297 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006298 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006299 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006300}
6301
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006302/// discard all CompoundStmts intervening between two constructs
6303static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006304 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006305 Body = CS->body_front();
6306
6307 return Body;
6308}
6309
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006310/// Emit the number of teams for a target directive. Inspect the num_teams
6311/// clause associated with a teams construct combined or closely nested
6312/// with the target directive.
6313///
6314/// Emit a team of size one for directives such as 'target parallel' that
6315/// have no associated teams construct.
6316///
6317/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006318static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006319emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6320 CodeGenFunction &CGF,
6321 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006322 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6323 "teams directive expected to be "
6324 "emitted only for the host!");
6325
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006326 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006327
6328 // If the target directive is combined with a teams directive:
6329 // Return the value in the num_teams clause, if any.
6330 // Otherwise, return 0 to denote the runtime default.
6331 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6332 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6333 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006334 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6335 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006336 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6337 /*IsSigned=*/true);
6338 }
6339
6340 // The default value is 0.
6341 return Bld.getInt32(0);
6342 }
6343
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006344 // If the target directive is combined with a parallel directive but not a
6345 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006346 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6347 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006348
6349 // If the current target region has a teams region enclosed, we need to get
6350 // the number of teams to pass to the runtime function call. This is done
6351 // by generating the expression in a inlined region. This is required because
6352 // the expression is captured in the enclosing target environment when the
6353 // teams directive is not combined with target.
6354
Alexey Bataev475a7442018-01-12 19:39:11 +00006355 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006356
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006357 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006358 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006359 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006360 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006361 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6362 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6363 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6364 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6365 /*IsSigned=*/true);
6366 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006367
Alexey Bataev50a1c782017-12-01 21:31:08 +00006368 // If we have an enclosed teams directive but no num_teams clause we use
6369 // the default value 0.
6370 return Bld.getInt32(0);
6371 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006372 }
6373
6374 // No teams associated with the directive.
6375 return nullptr;
6376}
6377
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006378/// Emit the number of threads for a target directive. Inspect the
6379/// thread_limit clause associated with a teams construct combined or closely
6380/// nested with the target directive.
6381///
6382/// Emit the num_threads clause for directives such as 'target parallel' that
6383/// have no associated teams construct.
6384///
6385/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006386static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006387emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6388 CodeGenFunction &CGF,
6389 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006390 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6391 "teams directive expected to be "
6392 "emitted only for the host!");
6393
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006394 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006395
6396 //
6397 // If the target directive is combined with a teams directive:
6398 // Return the value in the thread_limit clause, if any.
6399 //
6400 // If the target directive is combined with a parallel directive:
6401 // Return the value in the num_threads clause, if any.
6402 //
6403 // If both clauses are set, select the minimum of the two.
6404 //
6405 // If neither teams or parallel combined directives set the number of threads
6406 // in a team, return 0 to denote the runtime default.
6407 //
6408 // If this is not a teams directive return nullptr.
6409
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006410 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6411 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006412 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6413 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006414 llvm::Value *ThreadLimitVal = nullptr;
6415
6416 if (const auto *ThreadLimitClause =
6417 D.getSingleClause<OMPThreadLimitClause>()) {
6418 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006419 llvm::Value *ThreadLimit =
6420 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6421 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006422 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6423 /*IsSigned=*/true);
6424 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006425
6426 if (const auto *NumThreadsClause =
6427 D.getSingleClause<OMPNumThreadsClause>()) {
6428 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6429 llvm::Value *NumThreads =
6430 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6431 /*IgnoreResultAssign*/ true);
6432 NumThreadsVal =
6433 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6434 }
6435
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006436 // Select the lesser of thread_limit and num_threads.
6437 if (NumThreadsVal)
6438 ThreadLimitVal = ThreadLimitVal
6439 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6440 ThreadLimitVal),
6441 NumThreadsVal, ThreadLimitVal)
6442 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006443
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006444 // Set default value passed to the runtime if either teams or a target
6445 // parallel type directive is found but no clause is specified.
6446 if (!ThreadLimitVal)
6447 ThreadLimitVal = DefaultThreadLimitVal;
6448
6449 return ThreadLimitVal;
6450 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006451
Samuel Antaob68e2db2016-03-03 16:20:23 +00006452 // If the current target region has a teams region enclosed, we need to get
6453 // the thread limit to pass to the runtime function call. This is done
6454 // by generating the expression in a inlined region. This is required because
6455 // the expression is captured in the enclosing target environment when the
6456 // teams directive is not combined with target.
6457
Alexey Bataev475a7442018-01-12 19:39:11 +00006458 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006459
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006460 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006461 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006462 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006463 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006464 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6465 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6466 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6467 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6468 /*IsSigned=*/true);
6469 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006470
Alexey Bataev50a1c782017-12-01 21:31:08 +00006471 // If we have an enclosed teams directive but no thread_limit clause we
6472 // use the default value 0.
6473 return CGF.Builder.getInt32(0);
6474 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006475 }
6476
6477 // No teams associated with the directive.
6478 return nullptr;
6479}
6480
Samuel Antao86ace552016-04-27 22:40:57 +00006481namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006482// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006483// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6484// It provides a convenient interface to obtain the information and generate
6485// code for that information.
6486class MappableExprsHandler {
6487public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006488 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006489 /// offloading.
6490 enum OpenMPOffloadMappingFlags {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006491 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006492 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006493 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006494 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006495 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006496 /// if it was already mapped before.
6497 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006498 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006499 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006500 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006501 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006502 /// pointer and the pointee should be mapped.
6503 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006504 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006505 /// passed to the target kernel as an argument.
6506 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006507 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006508 /// in the current position for the data being mapped. Used when we have the
6509 /// use_device_ptr clause.
6510 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006511 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006512 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006513 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006514 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006515 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006516 /// Implicit map
6517 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006518 };
6519
Samuel Antaocc10b852016-07-28 14:23:26 +00006520 /// Class that associates information with a base pointer to be passed to the
6521 /// runtime library.
6522 class BasePointerInfo {
6523 /// The base pointer.
6524 llvm::Value *Ptr = nullptr;
6525 /// The base declaration that refers to this device pointer, or null if
6526 /// there is none.
6527 const ValueDecl *DevPtrDecl = nullptr;
6528
6529 public:
6530 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6531 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6532 llvm::Value *operator*() const { return Ptr; }
6533 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6534 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6535 };
6536
6537 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006538 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006539 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006540
6541private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006542 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006543 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006544
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006545 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006546 CodeGenFunction &CGF;
6547
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006548 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006549 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006550 /// Set of all reduction variables in the current directive.
6551 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006552
Samuel Antao6890b092016-07-28 14:25:09 +00006553 /// Map between device pointer declarations and their expression components.
6554 /// The key value for declarations in 'this' is null.
6555 llvm::DenseMap<
6556 const ValueDecl *,
6557 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6558 DevPointersMap;
6559
Samuel Antao86ace552016-04-27 22:40:57 +00006560 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006561 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006562
6563 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006564 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006565 ExprTy = RefTy->getPointeeType().getCanonicalType();
6566
6567 // Given that an array section is considered a built-in type, we need to
6568 // do the calculation based on the length of the section instead of relying
6569 // on CGF.getTypeSize(E->getType()).
6570 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6571 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6572 OAE->getBase()->IgnoreParenImpCasts())
6573 .getCanonicalType();
6574
6575 // If there is no length associated with the expression, that means we
6576 // are using the whole length of the base.
6577 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6578 return CGF.getTypeSize(BaseTy);
6579
6580 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006581 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006582 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006583 } else {
6584 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006585 assert(ATy && "Expecting array type if not a pointer type.");
6586 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6587 }
6588
6589 // If we don't have a length at this point, that is because we have an
6590 // array section with a single element.
6591 if (!OAE->getLength())
6592 return ElemSize;
6593
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006594 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006595 LengthVal =
6596 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6597 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6598 }
6599 return CGF.getTypeSize(ExprTy);
6600 }
6601
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006602 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006603 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006604 /// map as the first one of a series of maps that relate to the same map
6605 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006606 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006607 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006608 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006609 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006610 switch (MapType) {
6611 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006612 case OMPC_MAP_release:
6613 // alloc and release is the default behavior in the runtime library, i.e.
6614 // if we don't pass any bits alloc/release that is what the runtime is
6615 // going to do. Therefore, we don't need to signal anything for these two
6616 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006617 break;
6618 case OMPC_MAP_to:
6619 Bits = OMP_MAP_TO;
6620 break;
6621 case OMPC_MAP_from:
6622 Bits = OMP_MAP_FROM;
6623 break;
6624 case OMPC_MAP_tofrom:
6625 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6626 break;
6627 case OMPC_MAP_delete:
6628 Bits = OMP_MAP_DELETE;
6629 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006630 default:
6631 llvm_unreachable("Unexpected map type!");
6632 break;
6633 }
6634 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006635 Bits |= OMP_MAP_PTR_AND_OBJ;
6636 if (AddIsTargetParamFlag)
6637 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006638 if (MapTypeModifier == OMPC_MAP_always)
6639 Bits |= OMP_MAP_ALWAYS;
6640 return Bits;
6641 }
6642
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006643 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006644 /// final array section, is one whose length can't be proved to be one.
6645 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006646 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006647
6648 // It is not an array section and therefore not a unity-size one.
6649 if (!OASE)
6650 return false;
6651
6652 // An array section with no colon always refer to a single element.
6653 if (OASE->getColonLoc().isInvalid())
6654 return false;
6655
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006656 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006657
6658 // If we don't have a length we have to check if the array has size 1
6659 // for this dimension. Also, we should always expect a length if the
6660 // base type is pointer.
6661 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006662 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6663 OASE->getBase()->IgnoreParenImpCasts())
6664 .getCanonicalType();
6665 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006666 return ATy->getSize().getSExtValue() != 1;
6667 // If we don't have a constant dimension length, we have to consider
6668 // the current section as having any size, so it is not necessarily
6669 // unitary. If it happen to be unity size, that's user fault.
6670 return true;
6671 }
6672
6673 // Check if the length evaluates to 1.
6674 llvm::APSInt ConstLength;
6675 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6676 return true; // Can have more that size 1.
6677
6678 return ConstLength.getSExtValue() != 1;
6679 }
6680
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006681 /// Return the adjusted map modifiers if the declaration a capture
Alexey Bataev92327c52018-03-26 16:40:55 +00006682 /// refers to appears in a first-private clause. This is expected to be used
6683 /// only with directives that start with 'target'.
6684 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6685 unsigned CurrentModifiers) {
6686 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6687
6688 // A first private variable captured by reference will use only the
6689 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6690 // declaration is known as first-private in this handler.
6691 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6692 return MappableExprsHandler::OMP_MAP_PRIVATE |
6693 MappableExprsHandler::OMP_MAP_TO;
6694 // Reduction variable will use only the 'private ptr' and 'map to_from'
6695 // flag.
6696 if (ReductionDecls.count(Cap.getCapturedVar())) {
6697 return MappableExprsHandler::OMP_MAP_TO |
6698 MappableExprsHandler::OMP_MAP_FROM;
6699 }
6700
6701 // We didn't modify anything.
6702 return CurrentModifiers;
6703 }
6704
6705public:
6706 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
6707 : CurDir(Dir), CGF(CGF) {
6708 // Extract firstprivate clause information.
6709 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006710 for (const Expr *D : C->varlists())
Alexey Bataev92327c52018-03-26 16:40:55 +00006711 FirstPrivateDecls.insert(
6712 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6713 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006714 for (const Expr *D : C->varlists()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00006715 ReductionDecls.insert(
6716 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6717 }
6718 }
6719 // Extract device pointer clause information.
6720 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006721 for (const auto &L : C->component_lists())
Alexey Bataev92327c52018-03-26 16:40:55 +00006722 DevPointersMap[L.first].push_back(L.second);
6723 }
6724
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006725 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006726 /// bits for the provided map type, map modifier, and expression components.
6727 /// \a IsFirstComponent should be set to true if the provided set of
6728 /// components is the first associated with a capture.
6729 void generateInfoForComponentList(
6730 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6731 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006732 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006733 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006734 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006735
6736 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006737 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006738 // base pointer, section pointer, size, flags
6739 // (to add to the ones that come from the map type and modifier).
6740 //
6741 // double d;
6742 // int i[100];
6743 // float *p;
6744 //
6745 // struct S1 {
6746 // int i;
6747 // float f[50];
6748 // }
6749 // struct S2 {
6750 // int i;
6751 // float f[50];
6752 // S1 s;
6753 // double *p;
6754 // struct S2 *ps;
6755 // }
6756 // S2 s;
6757 // S2 *ps;
6758 //
6759 // map(d)
6760 // &d, &d, sizeof(double), noflags
6761 //
6762 // map(i)
6763 // &i, &i, 100*sizeof(int), noflags
6764 //
6765 // map(i[1:23])
6766 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6767 //
6768 // map(p)
6769 // &p, &p, sizeof(float*), noflags
6770 //
6771 // map(p[1:24])
6772 // p, &p[1], 24*sizeof(float), noflags
6773 //
6774 // map(s)
6775 // &s, &s, sizeof(S2), noflags
6776 //
6777 // map(s.i)
6778 // &s, &(s.i), sizeof(int), noflags
6779 //
6780 // map(s.s.f)
6781 // &s, &(s.i.f), 50*sizeof(int), noflags
6782 //
6783 // map(s.p)
6784 // &s, &(s.p), sizeof(double*), noflags
6785 //
6786 // map(s.p[:22], s.a s.b)
6787 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006788 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006789 //
6790 // map(s.ps)
6791 // &s, &(s.ps), sizeof(S2*), noflags
6792 //
6793 // map(s.ps->s.i)
6794 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006795 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006796 //
6797 // map(s.ps->ps)
6798 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006799 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006800 //
6801 // map(s.ps->ps->ps)
6802 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006803 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6804 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006805 //
6806 // map(s.ps->ps->s.f[:22])
6807 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006808 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6809 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006810 //
6811 // map(ps)
6812 // &ps, &ps, sizeof(S2*), noflags
6813 //
6814 // map(ps->i)
6815 // ps, &(ps->i), sizeof(int), noflags
6816 //
6817 // map(ps->s.f)
6818 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6819 //
6820 // map(ps->p)
6821 // ps, &(ps->p), sizeof(double*), noflags
6822 //
6823 // map(ps->p[:22])
6824 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006825 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006826 //
6827 // map(ps->ps)
6828 // ps, &(ps->ps), sizeof(S2*), noflags
6829 //
6830 // map(ps->ps->s.i)
6831 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006832 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006833 //
6834 // map(ps->ps->ps)
6835 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006836 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006837 //
6838 // map(ps->ps->ps->ps)
6839 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006840 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6841 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006842 //
6843 // map(ps->ps->ps->s.f[:22])
6844 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006845 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6846 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006847
6848 // Track if the map information being generated is the first for a capture.
6849 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006850 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006851
6852 // Scan the components from the base to the complete expression.
6853 auto CI = Components.rbegin();
6854 auto CE = Components.rend();
6855 auto I = CI;
6856
6857 // Track if the map information being generated is the first for a list of
6858 // components.
6859 bool IsExpressionFirstInfo = true;
6860 llvm::Value *BP = nullptr;
6861
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006862 if (const auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006863 // The base is the 'this' pointer. The content of the pointer is going
6864 // to be the base of the field being mapped.
6865 BP = CGF.EmitScalarExpr(ME->getBase());
6866 } else {
6867 // The base is the reference to the variable.
6868 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006869 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataev92327c52018-03-26 16:40:55 +00006870 if (const auto *VD =
6871 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6872 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006873 isDeclareTargetDeclaration(VD))
6874 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
6875 IsLink = true;
6876 BP = CGF.CGM.getOpenMPRuntime()
6877 .getAddrOfDeclareTargetLink(VD)
6878 .getPointer();
6879 }
Alexey Bataev92327c52018-03-26 16:40:55 +00006880 }
Samuel Antao86ace552016-04-27 22:40:57 +00006881
6882 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006883 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006884 // reference. References are ignored for mapping purposes.
6885 QualType Ty =
6886 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6887 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006888 LValue PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006889 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006890 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006891 .getPointer();
6892
6893 // We do not need to generate individual map information for the
6894 // pointer, it can be associated with the combined storage.
6895 ++I;
6896 }
6897 }
6898
George Rokos63bc9d62017-11-21 18:25:12 +00006899 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006900 for (; I != CE; ++I) {
6901 auto Next = std::next(I);
6902
6903 // We need to generate the addresses and sizes if this is the last
6904 // component, if the component is a pointer or if it is an array section
6905 // whose length can't be proved to be one. If this is a pointer, it
6906 // becomes the base address for the following components.
6907
6908 // A final array section, is one whose length can't be proved to be one.
6909 bool IsFinalArraySection =
6910 isFinalArraySectionExpression(I->getAssociatedExpression());
6911
6912 // Get information on whether the element is a pointer. Have to do a
6913 // special treatment for array sections given that they are built-in
6914 // types.
6915 const auto *OASE =
6916 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6917 bool IsPointer =
6918 (OASE &&
6919 OMPArraySectionExpr::getBaseOriginalType(OASE)
6920 .getCanonicalType()
6921 ->isAnyPointerType()) ||
6922 I->getAssociatedExpression()->getType()->isAnyPointerType();
6923
6924 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00006925 // If this is not the last component, we expect the pointer to be
6926 // associated with an array expression or member expression.
6927 assert((Next == CE ||
6928 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6929 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6930 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6931 "Unexpected expression");
6932
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006933 llvm::Value *LB =
6934 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006935 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Samuel Antao86ace552016-04-27 22:40:57 +00006936
Samuel Antao03a3cec2016-07-27 22:52:16 +00006937 // If we have a member expression and the current component is a
6938 // reference, we have to map the reference too. Whenever we have a
6939 // reference, the section that reference refers to is going to be a
6940 // load instruction from the storage assigned to the reference.
6941 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6942 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6943 auto *LI = cast<llvm::LoadInst>(LB);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006944 llvm::Value *RefAddr = LI->getPointerOperand();
Samuel Antao03a3cec2016-07-27 22:52:16 +00006945
6946 BasePointers.push_back(BP);
6947 Pointers.push_back(RefAddr);
6948 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006949 Types.push_back(DefaultFlags |
6950 getMapTypeBits(
6951 /*MapType*/ OMPC_MAP_alloc,
6952 /*MapTypeModifier=*/OMPC_MAP_unknown,
6953 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006954 IsExpressionFirstInfo = false;
6955 IsCaptureFirstInfo = false;
6956 // The reference will be the next base address.
6957 BP = RefAddr;
6958 }
6959
6960 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006961 Pointers.push_back(LB);
6962 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006963
Samuel Antao6782e942016-05-26 16:48:10 +00006964 // We need to add a pointer flag for each map that comes from the
6965 // same expression except for the first one. We also need to signal
6966 // this map is the first one that relates with the current capture
6967 // (there is a set of entries for each capture).
Alexey Bataev92327c52018-03-26 16:40:55 +00006968 Types.push_back(DefaultFlags |
6969 getMapTypeBits(MapType, MapTypeModifier,
6970 !IsExpressionFirstInfo || IsLink,
6971 IsCaptureFirstInfo && !IsLink));
Samuel Antao86ace552016-04-27 22:40:57 +00006972
6973 // If we have a final array section, we are done with this expression.
6974 if (IsFinalArraySection)
6975 break;
6976
6977 // The pointer becomes the base for the next element.
6978 if (Next != CE)
6979 BP = LB;
6980
6981 IsExpressionFirstInfo = false;
6982 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006983 }
6984 }
6985 }
6986
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006987 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006988 /// types for the extracted mappable expressions. Also, for each item that
6989 /// relates with a device pointer, a pair of the relevant declaration and
6990 /// index where it occurs is appended to the device pointers info array.
6991 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006992 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6993 MapFlagsArrayTy &Types) const {
6994 BasePointers.clear();
6995 Pointers.clear();
6996 Sizes.clear();
6997 Types.clear();
6998
6999 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00007000 /// Kind that defines how a device pointer has to be returned.
7001 enum ReturnPointerKind {
7002 // Don't have to return any pointer.
7003 RPK_None,
7004 // Pointer is the base of the declaration.
7005 RPK_Base,
7006 // Pointer is a member of the base declaration - 'this'
7007 RPK_Member,
7008 // Pointer is a reference and a member of the base declaration - 'this'
7009 RPK_MemberReference,
7010 };
Samuel Antao86ace552016-04-27 22:40:57 +00007011 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007012 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
7013 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
7014 ReturnPointerKind ReturnDevicePointer = RPK_None;
7015 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00007016
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007017 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00007018 MapInfo(
7019 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
7020 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007021 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00007022 : Components(Components), MapType(MapType),
7023 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007024 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00007025 };
7026
7027 // We have to process the component lists that relate with the same
7028 // declaration in a single chunk so that we can generate the map flags
7029 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007030 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007031
7032 // Helper function to fill the information map for the different supported
7033 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007034 auto &&InfoGen = [&Info](
7035 const ValueDecl *D,
7036 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7037 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007038 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007039 const ValueDecl *VD =
7040 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007041 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7042 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007043 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007044
Paul Robinson78fb1322016-08-01 22:12:46 +00007045 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007046 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7047 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007048 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007049 MapInfo::RPK_None, C->isImplicit());
7050 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007051 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7052 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007053 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007054 MapInfo::RPK_None, C->isImplicit());
7055 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007056 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7057 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007058 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007059 MapInfo::RPK_None, C->isImplicit());
7060 }
Samuel Antao86ace552016-04-27 22:40:57 +00007061
Samuel Antaocc10b852016-07-28 14:23:26 +00007062 // Look at the use_device_ptr clause information and mark the existing map
7063 // entries as such. If there is no map information for an entry in the
7064 // use_device_ptr list, we create one with map type 'alloc' and zero size
7065 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00007066 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007067 for (const auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
7068 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007069 assert(!L.second.empty() && "Not expecting empty list of components!");
7070 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7071 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007072 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007073 // If the first component is a member expression, we have to look into
7074 // 'this', which maps to null in the map of map information. Otherwise
7075 // look directly for the information.
7076 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7077
7078 // We potentially have map information for this declaration already.
7079 // Look for the first set of components that refer to it.
7080 if (It != Info.end()) {
7081 auto CI = std::find_if(
7082 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7083 return MI.Components.back().getAssociatedDeclaration() == VD;
7084 });
7085 // If we found a map entry, signal that the pointer has to be returned
7086 // and move on to the next declaration.
7087 if (CI != It->second.end()) {
7088 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
7089 ? (VD->getType()->isReferenceType()
7090 ? MapInfo::RPK_MemberReference
7091 : MapInfo::RPK_Member)
7092 : MapInfo::RPK_Base;
7093 continue;
7094 }
7095 }
7096
7097 // We didn't find any match in our map information - generate a zero
7098 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00007099 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataev1e491372018-01-23 18:44:14 +00007100 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(this->CGF.EmitLValue(IE),
7101 IE->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +00007102 BasePointers.push_back({Ptr, VD});
7103 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00007104 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00007105 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00007106 }
7107
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007108 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007109 // We need to know when we generate information for the first component
7110 // associated with a capture, because the mapping flags depend on it.
7111 bool IsFirstComponentList = true;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007112 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007113 assert(!L.Components.empty() &&
7114 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007115
7116 // Remember the current base pointer index.
7117 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007118 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007119 this->generateInfoForComponentList(
7120 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
7121 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007122
7123 // If this entry relates with a device pointer, set the relevant
7124 // declaration and add the 'return pointer' flag.
7125 if (IsFirstComponentList &&
7126 L.ReturnDevicePointer != MapInfo::RPK_None) {
7127 // If the pointer is not the base of the map, we need to skip the
7128 // base. If it is a reference in a member field, we also need to skip
7129 // the map of the reference.
7130 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
7131 ++CurrentBasePointersIdx;
7132 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
7133 ++CurrentBasePointersIdx;
7134 }
7135 assert(BasePointers.size() > CurrentBasePointersIdx &&
7136 "Unexpected number of mapped base pointers.");
7137
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007138 const ValueDecl *RelevantVD =
7139 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007140 assert(RelevantVD &&
7141 "No relevant declaration related with device pointer??");
7142
7143 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00007144 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007145 }
Samuel Antao86ace552016-04-27 22:40:57 +00007146 IsFirstComponentList = false;
7147 }
7148 }
7149 }
7150
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007151 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007152 /// associated to a given capture.
7153 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007154 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007155 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007156 MapValuesArrayTy &Pointers,
7157 MapValuesArrayTy &Sizes,
7158 MapFlagsArrayTy &Types) const {
7159 assert(!Cap->capturesVariableArrayType() &&
7160 "Not expecting to generate map info for a variable array type!");
7161
7162 BasePointers.clear();
7163 Pointers.clear();
7164 Sizes.clear();
7165 Types.clear();
7166
Samuel Antao6890b092016-07-28 14:25:09 +00007167 // We need to know when we generating information for the first component
7168 // associated with a capture, because the mapping flags depend on it.
7169 bool IsFirstComponentList = true;
7170
Samuel Antao86ace552016-04-27 22:40:57 +00007171 const ValueDecl *VD =
7172 Cap->capturesThis()
7173 ? nullptr
George Burgess IV00f70bd2018-03-01 05:43:23 +00007174 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007175
Samuel Antao6890b092016-07-28 14:25:09 +00007176 // If this declaration appears in a is_device_ptr clause we just have to
7177 // pass the pointer by value. If it is a reference to a declaration, we just
7178 // pass its value, otherwise, if it is a member expression, we need to map
7179 // 'to' the field.
7180 if (!VD) {
7181 auto It = DevPointersMap.find(VD);
7182 if (It != DevPointersMap.end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007183 for (ArrayRef<OMPClauseMappableExprCommon::MappableComponent> L :
7184 It->second) {
Samuel Antao6890b092016-07-28 14:25:09 +00007185 generateInfoForComponentList(
7186 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007187 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
7188 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00007189 IsFirstComponentList = false;
7190 }
7191 return;
7192 }
7193 } else if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007194 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007195 Pointers.push_back(Arg);
7196 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007197 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007198 return;
7199 }
7200
Paul Robinson78fb1322016-08-01 22:12:46 +00007201 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007202 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7203 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007204 assert(L.first == VD &&
7205 "We got information for the wrong declaration??");
7206 assert(!L.second.empty() &&
7207 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007208 generateInfoForComponentList(
7209 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7210 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007211 IsFirstComponentList = false;
7212 }
7213
7214 return;
7215 }
Samuel Antaod486f842016-05-26 16:53:38 +00007216
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007217 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007218 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007219 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7220 const FieldDecl &RI, llvm::Value *CV,
7221 MapBaseValuesArrayTy &CurBasePointers,
7222 MapValuesArrayTy &CurPointers,
7223 MapValuesArrayTy &CurSizes,
7224 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00007225
7226 // Do the default mapping.
7227 if (CI.capturesThis()) {
7228 CurBasePointers.push_back(CV);
7229 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007230 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007231 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7232 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007233 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007234 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007235 CurBasePointers.push_back(CV);
7236 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007237 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007238 // We have to signal to the runtime captures passed by value that are
7239 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007240 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007241 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7242 } else {
7243 // Pointers are implicitly mapped with a zero size and no flags
7244 // (other than first map that is added for all implicit maps).
7245 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00007246 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7247 }
7248 } else {
7249 assert(CI.capturesVariable() && "Expected captured reference.");
7250 CurBasePointers.push_back(CV);
7251 CurPointers.push_back(CV);
7252
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007253 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007254 QualType ElementType = PtrTy->getPointeeType();
7255 CurSizes.push_back(CGF.getTypeSize(ElementType));
7256 // The default map type for a scalar/complex type is 'to' because by
7257 // default the value doesn't have to be retrieved. For an aggregate
7258 // type, the default is 'tofrom'.
Alexey Bataev3f96fe62017-12-13 17:31:39 +00007259 CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
7260 CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
7261 : OMP_MAP_TO));
Samuel Antaod486f842016-05-26 16:53:38 +00007262 }
George Rokos065755d2017-11-07 18:27:04 +00007263 // Every default map produces a single argument which is a target parameter.
7264 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00007265 }
Samuel Antao86ace552016-04-27 22:40:57 +00007266};
Samuel Antaodf158d52016-04-27 22:58:19 +00007267
7268enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007269 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007270 /// from environment variables in the spec.
7271 OMP_DEVICEID_UNDEF = -1,
7272};
7273} // anonymous namespace
7274
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007275/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007276/// offloading runtime library. If there is no map or capture information,
7277/// return nullptr by reference.
7278static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007279emitOffloadingArrays(CodeGenFunction &CGF,
7280 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007281 MappableExprsHandler::MapValuesArrayTy &Pointers,
7282 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007283 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7284 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007285 CodeGenModule &CGM = CGF.CGM;
7286 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007287
Samuel Antaocc10b852016-07-28 14:23:26 +00007288 // Reset the array information.
7289 Info.clearArrayInfo();
7290 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007291
Samuel Antaocc10b852016-07-28 14:23:26 +00007292 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007293 // Detect if we have any capture size requiring runtime evaluation of the
7294 // size so that a constant array could be eventually used.
7295 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007296 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007297 if (!isa<llvm::Constant>(S)) {
7298 hasRuntimeEvaluationCaptureSize = true;
7299 break;
7300 }
7301
Samuel Antaocc10b852016-07-28 14:23:26 +00007302 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007303 QualType PointerArrayType =
7304 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7305 /*IndexTypeQuals=*/0);
7306
Samuel Antaocc10b852016-07-28 14:23:26 +00007307 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007308 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007309 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007310 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7311
7312 // If we don't have any VLA types or other types that require runtime
7313 // evaluation, we can use a constant array for the map sizes, otherwise we
7314 // need to fill up the arrays as we do for the pointers.
7315 if (hasRuntimeEvaluationCaptureSize) {
7316 QualType SizeArrayType = Ctx.getConstantArrayType(
7317 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7318 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007319 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007320 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7321 } else {
7322 // We expect all the sizes to be constant, so we collect them to create
7323 // a constant array.
7324 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007325 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007326 ConstSizes.push_back(cast<llvm::Constant>(S));
7327
7328 auto *SizesArrayInit = llvm::ConstantArray::get(
7329 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007330 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007331 auto *SizesArrayGbl = new llvm::GlobalVariable(
7332 CGM.getModule(), SizesArrayInit->getType(),
7333 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007334 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007335 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007336 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007337 }
7338
7339 // The map types are always constant so we don't need to generate code to
7340 // fill arrays. Instead, we create an array constant.
7341 llvm::Constant *MapTypesArrayInit =
7342 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007343 std::string MaptypesName =
7344 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007345 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7346 CGM.getModule(), MapTypesArrayInit->getType(),
7347 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007348 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007349 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007350 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007351
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007352 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7353 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007354 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007355 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007356 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007357 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7358 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007359 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7360 CGF.Builder.CreateStore(BPVal, BPAddr);
7361
Samuel Antaocc10b852016-07-28 14:23:26 +00007362 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007363 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007364 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007365
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007366 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007367 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007368 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007369 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007370 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7371 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007372 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7373 CGF.Builder.CreateStore(PVal, PAddr);
7374
7375 if (hasRuntimeEvaluationCaptureSize) {
7376 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007377 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7378 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007379 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007380 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00007381 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7382 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007383 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00007384 SAddr);
7385 }
7386 }
7387 }
7388}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007389/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00007390/// arrays of pointers, sizes and map types.
7391static void emitOffloadingArraysArgument(
7392 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7393 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007394 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007395 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007396 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007397 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007398 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7399 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007400 /*Idx0=*/0, /*Idx1=*/0);
7401 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007402 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7403 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007404 /*Idx0=*/0,
7405 /*Idx1=*/0);
7406 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007407 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007408 /*Idx0=*/0, /*Idx1=*/0);
7409 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007410 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007411 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007412 /*Idx0=*/0,
7413 /*Idx1=*/0);
7414 } else {
7415 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7416 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7417 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7418 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007419 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007420 }
Samuel Antao86ace552016-04-27 22:40:57 +00007421}
7422
Samuel Antaobed3c462015-10-02 16:14:20 +00007423void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7424 const OMPExecutableDirective &D,
7425 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007426 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007427 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007428 if (!CGF.HaveInsertPoint())
7429 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007430
Samuel Antaoee8fb302016-01-06 13:42:12 +00007431 assert(OutlinedFn && "Invalid outlined function!");
7432
Alexey Bataev8451efa2018-01-15 19:06:12 +00007433 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7434 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007435 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007436 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7437 PrePostActionTy &) {
7438 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7439 };
7440 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007441
Alexey Bataev8451efa2018-01-15 19:06:12 +00007442 CodeGenFunction::OMPTargetDataInfo InputInfo;
7443 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007444 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007445 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7446 &MapTypesArray, &CS, RequiresOuterTask,
7447 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007448 // On top of the arrays that were filled up, the target offloading call
7449 // takes as arguments the device id as well as the host pointer. The host
7450 // pointer is used by the runtime library to identify the current target
7451 // region, so it only has to be unique and not necessarily point to
7452 // anything. It could be the pointer to the outlined function that
7453 // implements the target region, but we aren't using that so that the
7454 // compiler doesn't need to keep that, and could therefore inline the host
7455 // function if proven worthwhile during optimization.
7456
Samuel Antaoee8fb302016-01-06 13:42:12 +00007457 // From this point on, we need to have an ID of the target region defined.
7458 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007459
7460 // Emit device ID if any.
7461 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007462 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007463 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007464 CGF.Int64Ty, /*isSigned=*/true);
7465 } else {
7466 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7467 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007468
Samuel Antaodf158d52016-04-27 22:58:19 +00007469 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007470 llvm::Value *PointerNum =
7471 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007472
Samuel Antaob68e2db2016-03-03 16:20:23 +00007473 // Return value of the runtime offloading call.
7474 llvm::Value *Return;
7475
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007476 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7477 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007478
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007479 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007480 // The target region is an outlined function launched by the runtime
7481 // via calls __tgt_target() or __tgt_target_teams().
7482 //
7483 // __tgt_target() launches a target region with one team and one thread,
7484 // executing a serial region. This master thread may in turn launch
7485 // more threads within its team upon encountering a parallel region,
7486 // however, no additional teams can be launched on the device.
7487 //
7488 // __tgt_target_teams() launches a target region with one or more teams,
7489 // each with one or more threads. This call is required for target
7490 // constructs such as:
7491 // 'target teams'
7492 // 'target' / 'teams'
7493 // 'target teams distribute parallel for'
7494 // 'target parallel'
7495 // and so on.
7496 //
7497 // Note that on the host and CPU targets, the runtime implementation of
7498 // these calls simply call the outlined function without forking threads.
7499 // The outlined functions themselves have runtime calls to
7500 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7501 // the compiler in emitTeamsCall() and emitParallelCall().
7502 //
7503 // In contrast, on the NVPTX target, the implementation of
7504 // __tgt_target_teams() launches a GPU kernel with the requested number
7505 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007506 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007507 // If we have NumTeams defined this means that we have an enclosed teams
7508 // region. Therefore we also expect to have NumThreads defined. These two
7509 // values should be defined in the presence of a teams directive,
7510 // regardless of having any clauses associated. If the user is using teams
7511 // but no clauses, these two values will be the default that should be
7512 // passed to the runtime library - a 32-bit integer with the value zero.
7513 assert(NumThreads && "Thread limit expression should be available along "
7514 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007515 llvm::Value *OffloadingArgs[] = {DeviceID,
7516 OutlinedFnID,
7517 PointerNum,
7518 InputInfo.BasePointersArray.getPointer(),
7519 InputInfo.PointersArray.getPointer(),
7520 InputInfo.SizesArray.getPointer(),
7521 MapTypesArray,
7522 NumTeams,
7523 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007524 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007525 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7526 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007527 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007528 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007529 llvm::Value *OffloadingArgs[] = {DeviceID,
7530 OutlinedFnID,
7531 PointerNum,
7532 InputInfo.BasePointersArray.getPointer(),
7533 InputInfo.PointersArray.getPointer(),
7534 InputInfo.SizesArray.getPointer(),
7535 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007536 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007537 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7538 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007539 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007540 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007541
Alexey Bataev2a007e02017-10-02 14:20:58 +00007542 // Check the error code and execute the host version if required.
7543 llvm::BasicBlock *OffloadFailedBlock =
7544 CGF.createBasicBlock("omp_offload.failed");
7545 llvm::BasicBlock *OffloadContBlock =
7546 CGF.createBasicBlock("omp_offload.cont");
7547 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7548 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7549
7550 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007551 if (RequiresOuterTask) {
7552 CapturedVars.clear();
7553 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7554 }
7555 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00007556 CGF.EmitBranch(OffloadContBlock);
7557
7558 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007559 };
7560
Samuel Antaoee8fb302016-01-06 13:42:12 +00007561 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007562 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7563 RequiresOuterTask](CodeGenFunction &CGF,
7564 PrePostActionTy &) {
7565 if (RequiresOuterTask) {
7566 CapturedVars.clear();
7567 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7568 }
7569 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7570 };
7571
7572 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7573 &CapturedVars, RequiresOuterTask,
7574 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7575 // Fill up the arrays with all the captured variables.
7576 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7577 MappableExprsHandler::MapValuesArrayTy Pointers;
7578 MappableExprsHandler::MapValuesArrayTy Sizes;
7579 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7580
7581 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7582 MappableExprsHandler::MapValuesArrayTy CurPointers;
7583 MappableExprsHandler::MapValuesArrayTy CurSizes;
7584 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7585
7586 // Get mappable expression information.
7587 MappableExprsHandler MEHandler(D, CGF);
7588
7589 auto RI = CS.getCapturedRecordDecl()->field_begin();
7590 auto CV = CapturedVars.begin();
7591 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7592 CE = CS.capture_end();
7593 CI != CE; ++CI, ++RI, ++CV) {
7594 CurBasePointers.clear();
7595 CurPointers.clear();
7596 CurSizes.clear();
7597 CurMapTypes.clear();
7598
7599 // VLA sizes are passed to the outlined region by copy and do not have map
7600 // information associated.
7601 if (CI->capturesVariableArrayType()) {
7602 CurBasePointers.push_back(*CV);
7603 CurPointers.push_back(*CV);
7604 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7605 // Copy to the device as an argument. No need to retrieve it.
7606 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7607 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7608 } else {
7609 // If we have any information in the map clause, we use it, otherwise we
7610 // just do a default mapping.
7611 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
7612 CurSizes, CurMapTypes);
7613 if (CurBasePointers.empty())
7614 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7615 CurPointers, CurSizes, CurMapTypes);
7616 }
7617 // We expect to have at least an element of information for this capture.
7618 assert(!CurBasePointers.empty() &&
7619 "Non-existing map pointer for capture!");
7620 assert(CurBasePointers.size() == CurPointers.size() &&
7621 CurBasePointers.size() == CurSizes.size() &&
7622 CurBasePointers.size() == CurMapTypes.size() &&
7623 "Inconsistent map information sizes!");
7624
7625 // We need to append the results of this capture to what we already have.
7626 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7627 Pointers.append(CurPointers.begin(), CurPointers.end());
7628 Sizes.append(CurSizes.begin(), CurSizes.end());
7629 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7630 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007631 // Map other list items in the map clause which are not captured variables
7632 // but "declare target link" global variables.
7633 for (const auto *C : D.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007634 for (const auto &L : C->component_lists()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00007635 if (!L.first)
7636 continue;
7637 const auto *VD = dyn_cast<VarDecl>(L.first);
7638 if (!VD)
7639 continue;
7640 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7641 isDeclareTargetDeclaration(VD);
7642 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7643 continue;
7644 MEHandler.generateInfoForComponentList(
7645 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7646 Pointers, Sizes, MapTypes, /*IsFirstComponentList=*/true,
7647 C->isImplicit());
7648 }
7649 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00007650
7651 TargetDataInfo Info;
7652 // Fill up the arrays and create the arguments.
7653 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7654 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7655 Info.PointersArray, Info.SizesArray,
7656 Info.MapTypesArray, Info);
7657 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7658 InputInfo.BasePointersArray =
7659 Address(Info.BasePointersArray, CGM.getPointerAlign());
7660 InputInfo.PointersArray =
7661 Address(Info.PointersArray, CGM.getPointerAlign());
7662 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7663 MapTypesArray = Info.MapTypesArray;
7664 if (RequiresOuterTask)
7665 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7666 else
7667 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7668 };
7669
7670 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7671 CodeGenFunction &CGF, PrePostActionTy &) {
7672 if (RequiresOuterTask) {
7673 CodeGenFunction::OMPTargetDataInfo InputInfo;
7674 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7675 } else {
7676 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7677 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007678 };
7679
7680 // If we have a target function ID it means that we need to support
7681 // offloading, otherwise, just execute on the host. We need to execute on host
7682 // regardless of the conditional in the if clause if, e.g., the user do not
7683 // specify target triples.
7684 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007685 if (IfCond) {
7686 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7687 } else {
7688 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007689 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007690 }
7691 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007692 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007693 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007694 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007695}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007696
7697void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7698 StringRef ParentName) {
7699 if (!S)
7700 return;
7701
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007702 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007703 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007704 isa<OMPExecutableDirective>(S) &&
7705 isOpenMPTargetExecutionDirective(
7706 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007707
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007708 if (RequiresDeviceCodegen) {
7709 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007710 unsigned DeviceID;
7711 unsigned FileID;
7712 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007713 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007714 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007715
7716 // Is this a target region that should not be emitted as an entry point? If
7717 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007718 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7719 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007720 return;
7721
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007722 switch (E.getDirectiveKind()) {
7723 case OMPD_target:
7724 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
7725 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007726 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007727 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007728 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007729 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007730 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007731 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007732 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007733 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007734 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007735 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007736 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007737 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007738 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007739 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007740 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007741 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007742 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007743 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007744 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007745 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007746 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007747 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007748 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007749 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007750 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007751 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00007752 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007753 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00007754 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007755 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00007756 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7757 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007758 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00007759 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007760 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00007761 CodeGenFunction::
7762 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7763 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007764 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00007765 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007766 case OMPD_parallel:
7767 case OMPD_for:
7768 case OMPD_parallel_for:
7769 case OMPD_parallel_sections:
7770 case OMPD_for_simd:
7771 case OMPD_parallel_for_simd:
7772 case OMPD_cancel:
7773 case OMPD_cancellation_point:
7774 case OMPD_ordered:
7775 case OMPD_threadprivate:
7776 case OMPD_task:
7777 case OMPD_simd:
7778 case OMPD_sections:
7779 case OMPD_section:
7780 case OMPD_single:
7781 case OMPD_master:
7782 case OMPD_critical:
7783 case OMPD_taskyield:
7784 case OMPD_barrier:
7785 case OMPD_taskwait:
7786 case OMPD_taskgroup:
7787 case OMPD_atomic:
7788 case OMPD_flush:
7789 case OMPD_teams:
7790 case OMPD_target_data:
7791 case OMPD_target_exit_data:
7792 case OMPD_target_enter_data:
7793 case OMPD_distribute:
7794 case OMPD_distribute_simd:
7795 case OMPD_distribute_parallel_for:
7796 case OMPD_distribute_parallel_for_simd:
7797 case OMPD_teams_distribute:
7798 case OMPD_teams_distribute_simd:
7799 case OMPD_teams_distribute_parallel_for:
7800 case OMPD_teams_distribute_parallel_for_simd:
7801 case OMPD_target_update:
7802 case OMPD_declare_simd:
7803 case OMPD_declare_target:
7804 case OMPD_end_declare_target:
7805 case OMPD_declare_reduction:
7806 case OMPD_taskloop:
7807 case OMPD_taskloop_simd:
7808 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007809 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7810 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007811 return;
7812 }
7813
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007814 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00007815 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007816 return;
7817
7818 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00007819 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007820 return;
7821 }
7822
7823 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007824 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007825 S = L->getBody();
7826
7827 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007828 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007829 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007830}
7831
7832bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007833 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007834
7835 // If emitting code for the host, we do not process FD here. Instead we do
7836 // the normal code generation.
7837 if (!CGM.getLangOpts().OpenMPIsDevice)
7838 return false;
7839
7840 // Try to detect target regions in the function.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007841 scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
Samuel Antaoee8fb302016-01-06 13:42:12 +00007842
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007843 // Do not to emit function if it is not marked as declare target.
Alexey Bataevfb388282018-05-01 14:09:46 +00007844 return !isDeclareTargetDeclaration(FD) &&
7845 AlreadyEmittedTargetFunctions.count(FD->getCanonicalDecl()) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007846}
7847
7848bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7849 if (!CGM.getLangOpts().OpenMPIsDevice)
7850 return false;
7851
7852 // Check if there are Ctors/Dtors in this declaration and look for target
7853 // regions in it. We use the complete variant to produce the kernel name
7854 // mangling.
7855 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007856 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7857 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00007858 StringRef ParentName =
7859 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7860 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7861 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007862 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00007863 StringRef ParentName =
7864 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7865 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7866 }
7867 }
7868
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007869 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00007870 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev03f270c2018-03-30 18:31:07 +00007871 isDeclareTargetDeclaration(cast<VarDecl>(GD.getDecl()));
Alexey Bataev92327c52018-03-26 16:40:55 +00007872 return !Res || *Res == OMPDeclareTargetDeclAttr::MT_Link;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007873}
7874
Alexey Bataev03f270c2018-03-30 18:31:07 +00007875void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
7876 llvm::Constant *Addr) {
7877 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7878 isDeclareTargetDeclaration(VD)) {
7879 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
7880 StringRef VarName;
7881 CharUnits VarSize;
7882 llvm::GlobalValue::LinkageTypes Linkage;
7883 switch (*Res) {
7884 case OMPDeclareTargetDeclAttr::MT_To:
7885 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7886 VarName = CGM.getMangledName(VD);
7887 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
7888 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
7889 break;
7890 case OMPDeclareTargetDeclAttr::MT_Link:
7891 // Map type 'to' because we do not map the original variable but the
7892 // reference.
7893 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7894 if (!CGM.getLangOpts().OpenMPIsDevice) {
7895 Addr =
7896 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
7897 }
7898 VarName = Addr->getName();
7899 VarSize = CGM.getPointerSize();
7900 Linkage = llvm::GlobalValue::WeakAnyLinkage;
7901 break;
7902 }
7903 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
7904 VarName, Addr, VarSize, Flags, Linkage);
7905 }
7906}
7907
Samuel Antaoee8fb302016-01-06 13:42:12 +00007908bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007909 if (isa<FunctionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007910 return emitTargetFunctions(GD);
7911
7912 return emitTargetGlobalVariable(GD);
7913}
7914
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007915CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
7916 CodeGenModule &CGM)
7917 : CGM(CGM) {
7918 if (CGM.getLangOpts().OpenMPIsDevice) {
7919 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
7920 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
7921 }
7922}
7923
7924CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
7925 if (CGM.getLangOpts().OpenMPIsDevice)
7926 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
7927}
7928
Alexey Bataev6d944102018-05-02 15:45:28 +00007929bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007930 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
7931 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007932
Alexey Bataev6d944102018-05-02 15:45:28 +00007933 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007934 const FunctionDecl *FD = D->getCanonicalDecl();
Alexey Bataev34f8a702018-03-28 14:28:54 +00007935 // Do not to emit function if it is marked as declare target as it was already
7936 // emitted.
7937 if (isDeclareTargetDeclaration(D)) {
7938 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
7939 if (auto *F = dyn_cast_or_null<llvm::Function>(
Alexey Bataev6d944102018-05-02 15:45:28 +00007940 CGM.GetGlobalValue(CGM.getMangledName(GD))))
Alexey Bataev34f8a702018-03-28 14:28:54 +00007941 return !F->isDeclaration();
7942 return false;
7943 }
7944 return true;
7945 }
7946
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007947 return !AlreadyEmittedTargetFunctions.insert(FD).second;
7948}
7949
Samuel Antaoee8fb302016-01-06 13:42:12 +00007950llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7951 // If we have offloading in the current module, we need to emit the entries
7952 // now and register the offloading descriptor.
7953 createOffloadEntriesAndInfoMetadata();
7954
7955 // Create and register the offloading binary descriptors. This is the main
7956 // entity that captures all the information about offloading in the current
7957 // compilation unit.
7958 return createOffloadingBinaryDescriptorRegistration();
7959}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007960
7961void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7962 const OMPExecutableDirective &D,
7963 SourceLocation Loc,
7964 llvm::Value *OutlinedFn,
7965 ArrayRef<llvm::Value *> CapturedVars) {
7966 if (!CGF.HaveInsertPoint())
7967 return;
7968
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007969 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007970 CodeGenFunction::RunCleanupsScope Scope(CGF);
7971
7972 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7973 llvm::Value *Args[] = {
7974 RTLoc,
7975 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7976 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7977 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7978 RealArgs.append(std::begin(Args), std::end(Args));
7979 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7980
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007981 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007982 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7983}
7984
7985void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007986 const Expr *NumTeams,
7987 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007988 SourceLocation Loc) {
7989 if (!CGF.HaveInsertPoint())
7990 return;
7991
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007992 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007993
Carlo Bertollic6872252016-04-04 15:55:02 +00007994 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007995 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00007996 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7997 CGF.CGM.Int32Ty, /* isSigned = */ true)
7998 : CGF.Builder.getInt32(0);
7999
8000 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008001 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008002 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8003 CGF.CGM.Int32Ty, /* isSigned = */ true)
8004 : CGF.Builder.getInt32(0);
8005
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008006 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008007 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8008 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008009 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8010 PushNumTeamsArgs);
8011}
Samuel Antaodf158d52016-04-27 22:58:19 +00008012
Samuel Antaocc10b852016-07-28 14:23:26 +00008013void CGOpenMPRuntime::emitTargetDataCalls(
8014 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8015 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008016 if (!CGF.HaveInsertPoint())
8017 return;
8018
Samuel Antaocc10b852016-07-28 14:23:26 +00008019 // Action used to replace the default codegen action and turn privatization
8020 // off.
8021 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008022
8023 // Generate the code for the opening of the data environment. Capture all the
8024 // arguments of the runtime call by reference because they are used in the
8025 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008026 auto &&BeginThenGen = [this, &D, Device, &Info,
8027 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008028 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008029 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008030 MappableExprsHandler::MapValuesArrayTy Pointers;
8031 MappableExprsHandler::MapValuesArrayTy Sizes;
8032 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8033
8034 // Get map clause information.
8035 MappableExprsHandler MCHandler(D, CGF);
8036 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008037
8038 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008039 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008040
8041 llvm::Value *BasePointersArrayArg = nullptr;
8042 llvm::Value *PointersArrayArg = nullptr;
8043 llvm::Value *SizesArrayArg = nullptr;
8044 llvm::Value *MapTypesArrayArg = nullptr;
8045 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008046 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008047
8048 // Emit device ID if any.
8049 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008050 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008051 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008052 CGF.Int64Ty, /*isSigned=*/true);
8053 } else {
8054 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8055 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008056
8057 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008058 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008059
8060 llvm::Value *OffloadingArgs[] = {
8061 DeviceID, PointerNum, BasePointersArrayArg,
8062 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008063 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008064 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008065
8066 // If device pointer privatization is required, emit the body of the region
8067 // here. It will have to be duplicated: with and without privatization.
8068 if (!Info.CaptureDeviceAddrMap.empty())
8069 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008070 };
8071
8072 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008073 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8074 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008075 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008076
8077 llvm::Value *BasePointersArrayArg = nullptr;
8078 llvm::Value *PointersArrayArg = nullptr;
8079 llvm::Value *SizesArrayArg = nullptr;
8080 llvm::Value *MapTypesArrayArg = nullptr;
8081 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008082 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008083
8084 // Emit device ID if any.
8085 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008086 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008087 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008088 CGF.Int64Ty, /*isSigned=*/true);
8089 } else {
8090 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8091 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008092
8093 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008094 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008095
8096 llvm::Value *OffloadingArgs[] = {
8097 DeviceID, PointerNum, BasePointersArrayArg,
8098 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008099 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008100 OffloadingArgs);
8101 };
8102
Samuel Antaocc10b852016-07-28 14:23:26 +00008103 // If we need device pointer privatization, we need to emit the body of the
8104 // region with no privatization in the 'else' branch of the conditional.
8105 // Otherwise, we don't have to do anything.
8106 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8107 PrePostActionTy &) {
8108 if (!Info.CaptureDeviceAddrMap.empty()) {
8109 CodeGen.setAction(NoPrivAction);
8110 CodeGen(CGF);
8111 }
8112 };
8113
8114 // We don't have to do anything to close the region if the if clause evaluates
8115 // to false.
8116 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008117
8118 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008119 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008120 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008121 RegionCodeGenTy RCG(BeginThenGen);
8122 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008123 }
8124
Samuel Antaocc10b852016-07-28 14:23:26 +00008125 // If we don't require privatization of device pointers, we emit the body in
8126 // between the runtime calls. This avoids duplicating the body code.
8127 if (Info.CaptureDeviceAddrMap.empty()) {
8128 CodeGen.setAction(NoPrivAction);
8129 CodeGen(CGF);
8130 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008131
8132 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008133 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008134 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008135 RegionCodeGenTy RCG(EndThenGen);
8136 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008137 }
8138}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008139
Samuel Antao8d2d7302016-05-26 18:30:22 +00008140void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008141 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8142 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008143 if (!CGF.HaveInsertPoint())
8144 return;
8145
Samuel Antao8dd66282016-04-27 23:14:30 +00008146 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008147 isa<OMPTargetExitDataDirective>(D) ||
8148 isa<OMPTargetUpdateDirective>(D)) &&
8149 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008150
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008151 CodeGenFunction::OMPTargetDataInfo InputInfo;
8152 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008153 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008154 auto &&ThenGen = [this, &D, Device, &InputInfo,
8155 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008156 // Emit device ID if any.
8157 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008158 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008159 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008160 CGF.Int64Ty, /*isSigned=*/true);
8161 } else {
8162 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8163 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008164
8165 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008166 llvm::Constant *PointerNum =
8167 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008168
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008169 llvm::Value *OffloadingArgs[] = {DeviceID,
8170 PointerNum,
8171 InputInfo.BasePointersArray.getPointer(),
8172 InputInfo.PointersArray.getPointer(),
8173 InputInfo.SizesArray.getPointer(),
8174 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008175
Samuel Antao8d2d7302016-05-26 18:30:22 +00008176 // Select the right runtime function call for each expected standalone
8177 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008178 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008179 OpenMPRTLFunction RTLFn;
8180 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008181 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008182 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8183 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008184 break;
8185 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008186 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8187 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008188 break;
8189 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008190 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8191 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008192 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008193 case OMPD_parallel:
8194 case OMPD_for:
8195 case OMPD_parallel_for:
8196 case OMPD_parallel_sections:
8197 case OMPD_for_simd:
8198 case OMPD_parallel_for_simd:
8199 case OMPD_cancel:
8200 case OMPD_cancellation_point:
8201 case OMPD_ordered:
8202 case OMPD_threadprivate:
8203 case OMPD_task:
8204 case OMPD_simd:
8205 case OMPD_sections:
8206 case OMPD_section:
8207 case OMPD_single:
8208 case OMPD_master:
8209 case OMPD_critical:
8210 case OMPD_taskyield:
8211 case OMPD_barrier:
8212 case OMPD_taskwait:
8213 case OMPD_taskgroup:
8214 case OMPD_atomic:
8215 case OMPD_flush:
8216 case OMPD_teams:
8217 case OMPD_target_data:
8218 case OMPD_distribute:
8219 case OMPD_distribute_simd:
8220 case OMPD_distribute_parallel_for:
8221 case OMPD_distribute_parallel_for_simd:
8222 case OMPD_teams_distribute:
8223 case OMPD_teams_distribute_simd:
8224 case OMPD_teams_distribute_parallel_for:
8225 case OMPD_teams_distribute_parallel_for_simd:
8226 case OMPD_declare_simd:
8227 case OMPD_declare_target:
8228 case OMPD_end_declare_target:
8229 case OMPD_declare_reduction:
8230 case OMPD_taskloop:
8231 case OMPD_taskloop_simd:
8232 case OMPD_target:
8233 case OMPD_target_simd:
8234 case OMPD_target_teams_distribute:
8235 case OMPD_target_teams_distribute_simd:
8236 case OMPD_target_teams_distribute_parallel_for:
8237 case OMPD_target_teams_distribute_parallel_for_simd:
8238 case OMPD_target_teams:
8239 case OMPD_target_parallel:
8240 case OMPD_target_parallel_for:
8241 case OMPD_target_parallel_for_simd:
8242 case OMPD_unknown:
8243 llvm_unreachable("Unexpected standalone target data directive.");
8244 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008245 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008246 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008247 };
8248
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008249 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8250 CodeGenFunction &CGF, PrePostActionTy &) {
8251 // Fill up the arrays with all the mapped variables.
8252 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8253 MappableExprsHandler::MapValuesArrayTy Pointers;
8254 MappableExprsHandler::MapValuesArrayTy Sizes;
8255 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008256
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008257 // Get map clause information.
8258 MappableExprsHandler MEHandler(D, CGF);
8259 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8260
8261 TargetDataInfo Info;
8262 // Fill up the arrays and create the arguments.
8263 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8264 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8265 Info.PointersArray, Info.SizesArray,
8266 Info.MapTypesArray, Info);
8267 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8268 InputInfo.BasePointersArray =
8269 Address(Info.BasePointersArray, CGM.getPointerAlign());
8270 InputInfo.PointersArray =
8271 Address(Info.PointersArray, CGM.getPointerAlign());
8272 InputInfo.SizesArray =
8273 Address(Info.SizesArray, CGM.getPointerAlign());
8274 MapTypesArray = Info.MapTypesArray;
8275 if (D.hasClausesOfKind<OMPDependClause>())
8276 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8277 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008278 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008279 };
8280
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008281 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008282 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8283 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008284 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008285 RegionCodeGenTy ThenRCG(TargetThenGen);
8286 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008287 }
8288}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008289
8290namespace {
8291 /// Kind of parameter in a function with 'declare simd' directive.
8292 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8293 /// Attribute set of the parameter.
8294 struct ParamAttrTy {
8295 ParamKindTy Kind = Vector;
8296 llvm::APSInt StrideOrArg;
8297 llvm::APSInt Alignment;
8298 };
8299} // namespace
8300
8301static unsigned evaluateCDTSize(const FunctionDecl *FD,
8302 ArrayRef<ParamAttrTy> ParamAttrs) {
8303 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8304 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8305 // of that clause. The VLEN value must be power of 2.
8306 // In other case the notion of the function`s "characteristic data type" (CDT)
8307 // is used to compute the vector length.
8308 // CDT is defined in the following order:
8309 // a) For non-void function, the CDT is the return type.
8310 // b) If the function has any non-uniform, non-linear parameters, then the
8311 // CDT is the type of the first such parameter.
8312 // c) If the CDT determined by a) or b) above is struct, union, or class
8313 // type which is pass-by-value (except for the type that maps to the
8314 // built-in complex data type), the characteristic data type is int.
8315 // d) If none of the above three cases is applicable, the CDT is int.
8316 // The VLEN is then determined based on the CDT and the size of vector
8317 // register of that ISA for which current vector version is generated. The
8318 // VLEN is computed using the formula below:
8319 // VLEN = sizeof(vector_register) / sizeof(CDT),
8320 // where vector register size specified in section 3.2.1 Registers and the
8321 // Stack Frame of original AMD64 ABI document.
8322 QualType RetType = FD->getReturnType();
8323 if (RetType.isNull())
8324 return 0;
8325 ASTContext &C = FD->getASTContext();
8326 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008327 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008328 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008329 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008330 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008331 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008332 if (ParamAttrs[Offset].Kind == Vector)
8333 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8334 ++Offset;
8335 }
8336 if (CDT.isNull()) {
8337 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8338 if (ParamAttrs[I + Offset].Kind == Vector) {
8339 CDT = FD->getParamDecl(I)->getType();
8340 break;
8341 }
8342 }
8343 }
8344 }
8345 if (CDT.isNull())
8346 CDT = C.IntTy;
8347 CDT = CDT->getCanonicalTypeUnqualified();
8348 if (CDT->isRecordType() || CDT->isUnionType())
8349 CDT = C.IntTy;
8350 return C.getTypeSize(CDT);
8351}
8352
8353static void
8354emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00008355 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008356 ArrayRef<ParamAttrTy> ParamAttrs,
8357 OMPDeclareSimdDeclAttr::BranchStateTy State) {
8358 struct ISADataTy {
8359 char ISA;
8360 unsigned VecRegSize;
8361 };
8362 ISADataTy ISAData[] = {
8363 {
8364 'b', 128
8365 }, // SSE
8366 {
8367 'c', 256
8368 }, // AVX
8369 {
8370 'd', 256
8371 }, // AVX2
8372 {
8373 'e', 512
8374 }, // AVX512
8375 };
8376 llvm::SmallVector<char, 2> Masked;
8377 switch (State) {
8378 case OMPDeclareSimdDeclAttr::BS_Undefined:
8379 Masked.push_back('N');
8380 Masked.push_back('M');
8381 break;
8382 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
8383 Masked.push_back('N');
8384 break;
8385 case OMPDeclareSimdDeclAttr::BS_Inbranch:
8386 Masked.push_back('M');
8387 break;
8388 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008389 for (char Mask : Masked) {
8390 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008391 SmallString<256> Buffer;
8392 llvm::raw_svector_ostream Out(Buffer);
8393 Out << "_ZGV" << Data.ISA << Mask;
8394 if (!VLENVal) {
8395 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
8396 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008397 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008398 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008399 }
8400 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008401 switch (ParamAttr.Kind){
8402 case LinearWithVarStride:
8403 Out << 's' << ParamAttr.StrideOrArg;
8404 break;
8405 case Linear:
8406 Out << 'l';
8407 if (!!ParamAttr.StrideOrArg)
8408 Out << ParamAttr.StrideOrArg;
8409 break;
8410 case Uniform:
8411 Out << 'u';
8412 break;
8413 case Vector:
8414 Out << 'v';
8415 break;
8416 }
8417 if (!!ParamAttr.Alignment)
8418 Out << 'a' << ParamAttr.Alignment;
8419 }
8420 Out << '_' << Fn->getName();
8421 Fn->addFnAttr(Out.str());
8422 }
8423 }
8424}
8425
8426void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
8427 llvm::Function *Fn) {
8428 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008429 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008430 // Map params to their positions in function decl.
8431 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
8432 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008433 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008434 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008435 for (const ParmVarDecl *P : FD->parameters()) {
8436 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008437 ++ParamPos;
8438 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008439 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008440 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008441 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
8442 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008443 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008444 E = E->IgnoreParenImpCasts();
8445 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008446 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008447 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008448 } else {
8449 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8450 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008451 Pos = ParamPositions[PVD];
8452 }
8453 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008454 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008455 // Get alignment info.
8456 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008457 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008458 E = E->IgnoreParenImpCasts();
8459 unsigned Pos;
8460 QualType ParmTy;
8461 if (isa<CXXThisExpr>(E)) {
8462 Pos = ParamPositions[FD];
8463 ParmTy = E->getType();
8464 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008465 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8466 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008467 Pos = ParamPositions[PVD];
8468 ParmTy = PVD->getType();
8469 }
8470 ParamAttrs[Pos].Alignment =
8471 (*NI)
8472 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008473 : llvm::APSInt::getUnsigned(
8474 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8475 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008476 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008477 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008478 // Mark linear parameters.
8479 auto SI = Attr->steps_begin();
8480 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008481 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008482 E = E->IgnoreParenImpCasts();
8483 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008484 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008485 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008486 } else {
8487 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8488 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008489 Pos = ParamPositions[PVD];
8490 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008491 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008492 ParamAttr.Kind = Linear;
8493 if (*SI) {
8494 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8495 Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008496 if (const auto *DRE =
8497 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
8498 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008499 ParamAttr.Kind = LinearWithVarStride;
8500 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
8501 ParamPositions[StridePVD->getCanonicalDecl()]);
8502 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008503 }
8504 }
8505 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008506 ++SI;
8507 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008508 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008509 llvm::APSInt VLENVal;
8510 if (const Expr *VLEN = Attr->getSimdlen())
8511 VLENVal = VLEN->EvaluateKnownConstInt(C);
8512 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
8513 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
8514 CGM.getTriple().getArch() == llvm::Triple::x86_64)
8515 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008516 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008517 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008518 }
8519}
Alexey Bataev8b427062016-05-25 12:36:08 +00008520
8521namespace {
8522/// Cleanup action for doacross support.
8523class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
8524public:
8525 static const int DoacrossFinArgs = 2;
8526
8527private:
8528 llvm::Value *RTLFn;
8529 llvm::Value *Args[DoacrossFinArgs];
8530
8531public:
8532 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
8533 : RTLFn(RTLFn) {
8534 assert(CallArgs.size() == DoacrossFinArgs);
8535 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
8536 }
8537 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
8538 if (!CGF.HaveInsertPoint())
8539 return;
8540 CGF.EmitRuntimeCall(RTLFn, Args);
8541 }
8542};
8543} // namespace
8544
8545void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8546 const OMPLoopDirective &D) {
8547 if (!CGF.HaveInsertPoint())
8548 return;
8549
8550 ASTContext &C = CGM.getContext();
8551 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
8552 RecordDecl *RD;
8553 if (KmpDimTy.isNull()) {
8554 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
8555 // kmp_int64 lo; // lower
8556 // kmp_int64 up; // upper
8557 // kmp_int64 st; // stride
8558 // };
8559 RD = C.buildImplicitRecord("kmp_dim");
8560 RD->startDefinition();
8561 addFieldToRecordDecl(C, RD, Int64Ty);
8562 addFieldToRecordDecl(C, RD, Int64Ty);
8563 addFieldToRecordDecl(C, RD, Int64Ty);
8564 RD->completeDefinition();
8565 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008566 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008567 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008568 }
Alexey Bataev8b427062016-05-25 12:36:08 +00008569
8570 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
8571 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
8572 enum { LowerFD = 0, UpperFD, StrideFD };
8573 // Fill dims with data.
8574 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
8575 // dims.upper = num_iterations;
8576 LValue UpperLVal =
8577 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
8578 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
8579 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
8580 Int64Ty, D.getNumIterations()->getExprLoc());
8581 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8582 // dims.stride = 1;
8583 LValue StrideLVal =
8584 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
8585 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8586 StrideLVal);
8587
8588 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8589 // kmp_int32 num_dims, struct kmp_dim * dims);
8590 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
8591 getThreadID(CGF, D.getLocStart()),
8592 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
8593 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8594 DimsAddr.getPointer(), CGM.VoidPtrTy)};
8595
8596 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8597 CGF.EmitRuntimeCall(RTLFn, Args);
8598 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
8599 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
8600 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8601 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8602 llvm::makeArrayRef(FiniArgs));
8603}
8604
8605void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8606 const OMPDependClause *C) {
8607 QualType Int64Ty =
8608 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8609 const Expr *CounterVal = C->getCounterValue();
8610 assert(CounterVal);
8611 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
8612 CounterVal->getType(), Int64Ty,
8613 CounterVal->getExprLoc());
8614 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
8615 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
8616 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
8617 getThreadID(CGF, C->getLocStart()),
8618 CntAddr.getPointer()};
8619 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008620 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00008621 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008622 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008623 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8624 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8625 }
8626 CGF.EmitRuntimeCall(RTLFn, Args);
8627}
8628
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008629void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8630 llvm::Value *Callee,
8631 ArrayRef<llvm::Value *> Args) const {
8632 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00008633 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8634
8635 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008636 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008637 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008638 return;
8639 }
8640 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008641 CGF.EmitRuntimeCall(Callee, Args);
8642}
8643
8644void CGOpenMPRuntime::emitOutlinedFunctionCall(
8645 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8646 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008647 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008648}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008649
8650Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8651 const VarDecl *NativeParam,
8652 const VarDecl *TargetParam) const {
8653 return CGF.GetAddrOfLocalVar(NativeParam);
8654}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008655
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00008656Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
8657 const VarDecl *VD) {
8658 return Address::invalid();
8659}
8660
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008661llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8662 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8663 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8664 llvm_unreachable("Not supported in SIMD-only mode");
8665}
8666
8667llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8668 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8669 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8670 llvm_unreachable("Not supported in SIMD-only mode");
8671}
8672
8673llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8674 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8675 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8676 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8677 bool Tied, unsigned &NumberOfParts) {
8678 llvm_unreachable("Not supported in SIMD-only mode");
8679}
8680
8681void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8682 SourceLocation Loc,
8683 llvm::Value *OutlinedFn,
8684 ArrayRef<llvm::Value *> CapturedVars,
8685 const Expr *IfCond) {
8686 llvm_unreachable("Not supported in SIMD-only mode");
8687}
8688
8689void CGOpenMPSIMDRuntime::emitCriticalRegion(
8690 CodeGenFunction &CGF, StringRef CriticalName,
8691 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8692 const Expr *Hint) {
8693 llvm_unreachable("Not supported in SIMD-only mode");
8694}
8695
8696void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8697 const RegionCodeGenTy &MasterOpGen,
8698 SourceLocation Loc) {
8699 llvm_unreachable("Not supported in SIMD-only mode");
8700}
8701
8702void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8703 SourceLocation Loc) {
8704 llvm_unreachable("Not supported in SIMD-only mode");
8705}
8706
8707void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8708 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8709 SourceLocation Loc) {
8710 llvm_unreachable("Not supported in SIMD-only mode");
8711}
8712
8713void CGOpenMPSIMDRuntime::emitSingleRegion(
8714 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8715 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8716 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8717 ArrayRef<const Expr *> AssignmentOps) {
8718 llvm_unreachable("Not supported in SIMD-only mode");
8719}
8720
8721void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8722 const RegionCodeGenTy &OrderedOpGen,
8723 SourceLocation Loc,
8724 bool IsThreads) {
8725 llvm_unreachable("Not supported in SIMD-only mode");
8726}
8727
8728void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8729 SourceLocation Loc,
8730 OpenMPDirectiveKind Kind,
8731 bool EmitChecks,
8732 bool ForceSimpleCall) {
8733 llvm_unreachable("Not supported in SIMD-only mode");
8734}
8735
8736void CGOpenMPSIMDRuntime::emitForDispatchInit(
8737 CodeGenFunction &CGF, SourceLocation Loc,
8738 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8739 bool Ordered, const DispatchRTInput &DispatchValues) {
8740 llvm_unreachable("Not supported in SIMD-only mode");
8741}
8742
8743void CGOpenMPSIMDRuntime::emitForStaticInit(
8744 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8745 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8746 llvm_unreachable("Not supported in SIMD-only mode");
8747}
8748
8749void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8750 CodeGenFunction &CGF, SourceLocation Loc,
8751 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8752 llvm_unreachable("Not supported in SIMD-only mode");
8753}
8754
8755void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8756 SourceLocation Loc,
8757 unsigned IVSize,
8758 bool IVSigned) {
8759 llvm_unreachable("Not supported in SIMD-only mode");
8760}
8761
8762void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
8763 SourceLocation Loc,
8764 OpenMPDirectiveKind DKind) {
8765 llvm_unreachable("Not supported in SIMD-only mode");
8766}
8767
8768llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
8769 SourceLocation Loc,
8770 unsigned IVSize, bool IVSigned,
8771 Address IL, Address LB,
8772 Address UB, Address ST) {
8773 llvm_unreachable("Not supported in SIMD-only mode");
8774}
8775
8776void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
8777 llvm::Value *NumThreads,
8778 SourceLocation Loc) {
8779 llvm_unreachable("Not supported in SIMD-only mode");
8780}
8781
8782void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
8783 OpenMPProcBindClauseKind ProcBind,
8784 SourceLocation Loc) {
8785 llvm_unreachable("Not supported in SIMD-only mode");
8786}
8787
8788Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
8789 const VarDecl *VD,
8790 Address VDAddr,
8791 SourceLocation Loc) {
8792 llvm_unreachable("Not supported in SIMD-only mode");
8793}
8794
8795llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
8796 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
8797 CodeGenFunction *CGF) {
8798 llvm_unreachable("Not supported in SIMD-only mode");
8799}
8800
8801Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
8802 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
8803 llvm_unreachable("Not supported in SIMD-only mode");
8804}
8805
8806void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
8807 ArrayRef<const Expr *> Vars,
8808 SourceLocation Loc) {
8809 llvm_unreachable("Not supported in SIMD-only mode");
8810}
8811
8812void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
8813 const OMPExecutableDirective &D,
8814 llvm::Value *TaskFunction,
8815 QualType SharedsTy, Address Shareds,
8816 const Expr *IfCond,
8817 const OMPTaskDataTy &Data) {
8818 llvm_unreachable("Not supported in SIMD-only mode");
8819}
8820
8821void CGOpenMPSIMDRuntime::emitTaskLoopCall(
8822 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
8823 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
8824 const Expr *IfCond, const OMPTaskDataTy &Data) {
8825 llvm_unreachable("Not supported in SIMD-only mode");
8826}
8827
8828void CGOpenMPSIMDRuntime::emitReduction(
8829 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
8830 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
8831 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
8832 assert(Options.SimpleReduction && "Only simple reduction is expected.");
8833 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
8834 ReductionOps, Options);
8835}
8836
8837llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
8838 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
8839 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
8840 llvm_unreachable("Not supported in SIMD-only mode");
8841}
8842
8843void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
8844 SourceLocation Loc,
8845 ReductionCodeGen &RCG,
8846 unsigned N) {
8847 llvm_unreachable("Not supported in SIMD-only mode");
8848}
8849
8850Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
8851 SourceLocation Loc,
8852 llvm::Value *ReductionsPtr,
8853 LValue SharedLVal) {
8854 llvm_unreachable("Not supported in SIMD-only mode");
8855}
8856
8857void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
8858 SourceLocation Loc) {
8859 llvm_unreachable("Not supported in SIMD-only mode");
8860}
8861
8862void CGOpenMPSIMDRuntime::emitCancellationPointCall(
8863 CodeGenFunction &CGF, SourceLocation Loc,
8864 OpenMPDirectiveKind CancelRegion) {
8865 llvm_unreachable("Not supported in SIMD-only mode");
8866}
8867
8868void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
8869 SourceLocation Loc, const Expr *IfCond,
8870 OpenMPDirectiveKind CancelRegion) {
8871 llvm_unreachable("Not supported in SIMD-only mode");
8872}
8873
8874void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
8875 const OMPExecutableDirective &D, StringRef ParentName,
8876 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
8877 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
8878 llvm_unreachable("Not supported in SIMD-only mode");
8879}
8880
8881void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
8882 const OMPExecutableDirective &D,
8883 llvm::Value *OutlinedFn,
8884 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008885 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008886 llvm_unreachable("Not supported in SIMD-only mode");
8887}
8888
8889bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
8890 llvm_unreachable("Not supported in SIMD-only mode");
8891}
8892
8893bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8894 llvm_unreachable("Not supported in SIMD-only mode");
8895}
8896
8897bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
8898 return false;
8899}
8900
8901llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
8902 return nullptr;
8903}
8904
8905void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
8906 const OMPExecutableDirective &D,
8907 SourceLocation Loc,
8908 llvm::Value *OutlinedFn,
8909 ArrayRef<llvm::Value *> CapturedVars) {
8910 llvm_unreachable("Not supported in SIMD-only mode");
8911}
8912
8913void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
8914 const Expr *NumTeams,
8915 const Expr *ThreadLimit,
8916 SourceLocation Loc) {
8917 llvm_unreachable("Not supported in SIMD-only mode");
8918}
8919
8920void CGOpenMPSIMDRuntime::emitTargetDataCalls(
8921 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8922 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8923 llvm_unreachable("Not supported in SIMD-only mode");
8924}
8925
8926void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
8927 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8928 const Expr *Device) {
8929 llvm_unreachable("Not supported in SIMD-only mode");
8930}
8931
8932void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8933 const OMPLoopDirective &D) {
8934 llvm_unreachable("Not supported in SIMD-only mode");
8935}
8936
8937void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8938 const OMPDependClause *C) {
8939 llvm_unreachable("Not supported in SIMD-only mode");
8940}
8941
8942const VarDecl *
8943CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
8944 const VarDecl *NativeParam) const {
8945 llvm_unreachable("Not supported in SIMD-only mode");
8946}
8947
8948Address
8949CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
8950 const VarDecl *NativeParam,
8951 const VarDecl *TargetParam) const {
8952 llvm_unreachable("Not supported in SIMD-only mode");
8953}
8954