blob: 6dd6dd4dcd828015bc31e4dc1085db4544a64e73 [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"
17#include "CodeGenFunction.h"
18#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000019#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "llvm/ADT/ArrayRef.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000021#include "llvm/Bitcode/ReaderWriter.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000026#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000027#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000028#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000029
30using namespace clang;
31using namespace CodeGen;
32
Benjamin Kramerc52193f2014-10-10 13:57:57 +000033namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000034/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000035class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
36public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000037 /// \brief Kinds of OpenMP regions used in codegen.
38 enum CGOpenMPRegionKind {
39 /// \brief Region with outlined function for standalone 'parallel'
40 /// directive.
41 ParallelOutlinedRegion,
42 /// \brief Region with outlined function for standalone 'task' directive.
43 TaskOutlinedRegion,
44 /// \brief Region for constructs that do not require function outlining,
45 /// like 'for', 'sections', 'atomic' etc. directives.
46 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000047 /// \brief Region with outlined function for standalone 'target' directive.
48 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000049 };
Alexey Bataev18095712014-10-10 12:19:54 +000050
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 CGOpenMPRegionInfo(const CapturedStmt &CS,
52 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000053 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
54 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000055 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057
58 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
60 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000061 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000063
64 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000065 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000069 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000071 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000072 /// \return LValue for thread id variable. This LValue always has type int32*.
73 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000074
Alexey Bataev48591dd2016-04-20 04:01:36 +000075 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
76
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000077 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000078
Alexey Bataev81c7ea02015-07-03 09:56:58 +000079 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
80
Alexey Bataev25e5b442015-09-15 12:52:43 +000081 bool hasCancel() const { return HasCancel; }
82
Alexey Bataev18095712014-10-10 12:19:54 +000083 static bool classof(const CGCapturedStmtInfo *Info) {
84 return Info->getKind() == CR_OpenMP;
85 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000086
Alexey Bataev48591dd2016-04-20 04:01:36 +000087 ~CGOpenMPRegionInfo() override = default;
88
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000089protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000090 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000091 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000092 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000093 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000094};
Alexey Bataev18095712014-10-10 12:19:54 +000095
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000097class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000098public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000099 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000100 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000101 OpenMPDirectiveKind Kind, bool HasCancel)
102 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
103 HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000104 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000105 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
106 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000107
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 /// \brief Get a variable or parameter for storing global thread id
109 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000110 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000111
Alexey Bataev18095712014-10-10 12:19:54 +0000112 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000113 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +0000114
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000115 static bool classof(const CGCapturedStmtInfo *Info) {
116 return CGOpenMPRegionInfo::classof(Info) &&
117 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
118 ParallelOutlinedRegion;
119 }
120
Alexey Bataev18095712014-10-10 12:19:54 +0000121private:
122 /// \brief A variable or parameter storing global thread id for OpenMP
123 /// constructs.
124 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000125};
126
Alexey Bataev62b63b12015-03-10 07:28:44 +0000127/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000128class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000129public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000130 class UntiedTaskActionTy final : public PrePostActionTy {
131 bool Untied;
132 const VarDecl *PartIDVar;
133 const RegionCodeGenTy UntiedCodeGen;
134 llvm::SwitchInst *UntiedSwitch = nullptr;
135
136 public:
137 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
138 const RegionCodeGenTy &UntiedCodeGen)
139 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
140 void Enter(CodeGenFunction &CGF) override {
141 if (Untied) {
142 // Emit task switching point.
143 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
144 CGF.GetAddrOfLocalVar(PartIDVar),
145 PartIDVar->getType()->castAs<PointerType>());
146 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
147 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
148 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
149 CGF.EmitBlock(DoneBB);
150 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
151 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
152 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
153 CGF.Builder.GetInsertBlock());
154 emitUntiedSwitch(CGF);
155 }
156 }
157 void emitUntiedSwitch(CodeGenFunction &CGF) const {
158 if (Untied) {
159 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
160 CGF.GetAddrOfLocalVar(PartIDVar),
161 PartIDVar->getType()->castAs<PointerType>());
162 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
163 PartIdLVal);
164 UntiedCodeGen(CGF);
165 CodeGenFunction::JumpDest CurPoint =
166 CGF.getJumpDestInCurrentScope(".untied.next.");
167 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
168 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
169 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
170 CGF.Builder.GetInsertBlock());
171 CGF.EmitBranchThroughCleanup(CurPoint);
172 CGF.EmitBlock(CurPoint.getBlock());
173 }
174 }
175 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
176 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000177 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000178 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000179 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000180 OpenMPDirectiveKind Kind, bool HasCancel,
181 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000182 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000183 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000184 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
185 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000186
Alexey Bataev62b63b12015-03-10 07:28:44 +0000187 /// \brief Get a variable or parameter for storing global thread id
188 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000189 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190
191 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000192 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000193
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194 /// \brief Get the name of the capture helper.
195 StringRef getHelperName() const override { return ".omp_outlined."; }
196
Alexey Bataev48591dd2016-04-20 04:01:36 +0000197 void emitUntiedSwitch(CodeGenFunction &CGF) override {
198 Action.emitUntiedSwitch(CGF);
199 }
200
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000201 static bool classof(const CGCapturedStmtInfo *Info) {
202 return CGOpenMPRegionInfo::classof(Info) &&
203 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
204 TaskOutlinedRegion;
205 }
206
Alexey Bataev62b63b12015-03-10 07:28:44 +0000207private:
208 /// \brief A variable or parameter storing global thread id for OpenMP
209 /// constructs.
210 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000211 /// Action for emitting code for untied tasks.
212 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000213};
214
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000215/// \brief API for inlined captured statement code generation in OpenMP
216/// constructs.
217class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
218public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000219 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000220 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000221 OpenMPDirectiveKind Kind, bool HasCancel)
222 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
223 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000224 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000225
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000226 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000227 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 if (OuterRegionInfo)
229 return OuterRegionInfo->getContextValue();
230 llvm_unreachable("No context value for inlined OpenMP region");
231 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000232
Hans Wennborg7eb54642015-09-10 17:07:54 +0000233 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000234 if (OuterRegionInfo) {
235 OuterRegionInfo->setContextValue(V);
236 return;
237 }
238 llvm_unreachable("No context value for inlined OpenMP region");
239 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000240
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000241 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000242 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000243 if (OuterRegionInfo)
244 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000245 // If there is no outer outlined region,no need to lookup in a list of
246 // captured variables, we can use the original one.
247 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000248 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000249
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000250 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000251 if (OuterRegionInfo)
252 return OuterRegionInfo->getThisFieldDecl();
253 return nullptr;
254 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000255
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000256 /// \brief Get a variable or parameter for storing global thread id
257 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000258 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000259 if (OuterRegionInfo)
260 return OuterRegionInfo->getThreadIDVariable();
261 return nullptr;
262 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000263
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000264 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000265 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000266 if (auto *OuterRegionInfo = getOldCSI())
267 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000268 llvm_unreachable("No helper name for inlined OpenMP construct");
269 }
270
Alexey Bataev48591dd2016-04-20 04:01:36 +0000271 void emitUntiedSwitch(CodeGenFunction &CGF) override {
272 if (OuterRegionInfo)
273 OuterRegionInfo->emitUntiedSwitch(CGF);
274 }
275
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000276 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
277
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000278 static bool classof(const CGCapturedStmtInfo *Info) {
279 return CGOpenMPRegionInfo::classof(Info) &&
280 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
281 }
282
Alexey Bataev48591dd2016-04-20 04:01:36 +0000283 ~CGOpenMPInlinedRegionInfo() override = default;
284
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000285private:
286 /// \brief CodeGen info about outer OpenMP region.
287 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
288 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000289};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000290
Samuel Antaobed3c462015-10-02 16:14:20 +0000291/// \brief API for captured statement code generation in OpenMP target
292/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000293/// captured fields. The name of the target region has to be unique in a given
294/// application so it is provided by the client, because only the client has
295/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000296class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000297public:
298 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000299 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000300 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000301 /*HasCancel=*/false),
302 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000303
304 /// \brief This is unused for target regions because each starts executing
305 /// with a single thread.
306 const VarDecl *getThreadIDVariable() const override { return nullptr; }
307
308 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000309 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000310
311 static bool classof(const CGCapturedStmtInfo *Info) {
312 return CGOpenMPRegionInfo::classof(Info) &&
313 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
314 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000315
316private:
317 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000318};
319
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000320static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000321 llvm_unreachable("No codegen for expressions");
322}
323/// \brief API for generation of expressions captured in a innermost OpenMP
324/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000325class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000326public:
327 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
328 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
329 OMPD_unknown,
330 /*HasCancel=*/false),
331 PrivScope(CGF) {
332 // Make sure the globals captured in the provided statement are local by
333 // using the privatization logic. We assume the same variable is not
334 // captured more than once.
335 for (auto &C : CS.captures()) {
336 if (!C.capturesVariable() && !C.capturesVariableByCopy())
337 continue;
338
339 const VarDecl *VD = C.getCapturedVar();
340 if (VD->isLocalVarDeclOrParm())
341 continue;
342
343 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
344 /*RefersToEnclosingVariableOrCapture=*/false,
345 VD->getType().getNonReferenceType(), VK_LValue,
346 SourceLocation());
347 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
348 return CGF.EmitLValue(&DRE).getAddress();
349 });
350 }
351 (void)PrivScope.Privatize();
352 }
353
354 /// \brief Lookup the captured field decl for a variable.
355 const FieldDecl *lookup(const VarDecl *VD) const override {
356 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
357 return FD;
358 return nullptr;
359 }
360
361 /// \brief Emit the captured statement body.
362 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
363 llvm_unreachable("No body for expressions");
364 }
365
366 /// \brief Get a variable or parameter for storing global thread id
367 /// inside OpenMP construct.
368 const VarDecl *getThreadIDVariable() const override {
369 llvm_unreachable("No thread id for expressions");
370 }
371
372 /// \brief Get the name of the capture helper.
373 StringRef getHelperName() const override {
374 llvm_unreachable("No helper name for expressions");
375 }
376
377 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
378
379private:
380 /// Private scope to capture global variables.
381 CodeGenFunction::OMPPrivateScope PrivScope;
382};
383
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000384/// \brief RAII for emitting code of OpenMP constructs.
385class InlinedOpenMPRegionRAII {
386 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000387 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
388 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000389
390public:
391 /// \brief Constructs region for combined constructs.
392 /// \param CodeGen Code generation sequence for combined directives. Includes
393 /// a list of functions used for code generation of implicitly inlined
394 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000395 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000396 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000397 : CGF(CGF) {
398 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000399 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
400 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000401 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
402 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
403 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000404 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000405
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000406 ~InlinedOpenMPRegionRAII() {
407 // Restore original CapturedStmtInfo only if we're done with code emission.
408 auto *OldCSI =
409 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
410 delete CGF.CapturedStmtInfo;
411 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000412 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
413 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000414 }
415};
416
Alexey Bataev50b3c952016-02-19 10:38:26 +0000417/// \brief Values for bit flags used in the ident_t to describe the fields.
418/// All enumeric elements are named and described in accordance with the code
419/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
420enum OpenMPLocationFlags {
421 /// \brief Use trampoline for internal microtask.
422 OMP_IDENT_IMD = 0x01,
423 /// \brief Use c-style ident structure.
424 OMP_IDENT_KMPC = 0x02,
425 /// \brief Atomic reduction option for kmpc_reduce.
426 OMP_ATOMIC_REDUCE = 0x10,
427 /// \brief Explicit 'barrier' directive.
428 OMP_IDENT_BARRIER_EXPL = 0x20,
429 /// \brief Implicit barrier in code.
430 OMP_IDENT_BARRIER_IMPL = 0x40,
431 /// \brief Implicit barrier in 'for' directive.
432 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
433 /// \brief Implicit barrier in 'sections' directive.
434 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
435 /// \brief Implicit barrier in 'single' directive.
436 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
437};
438
439/// \brief Describes ident structure that describes a source location.
440/// All descriptions are taken from
441/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
442/// Original structure:
443/// typedef struct ident {
444/// kmp_int32 reserved_1; /**< might be used in Fortran;
445/// see above */
446/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
447/// KMP_IDENT_KMPC identifies this union
448/// member */
449/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
450/// see above */
451///#if USE_ITT_BUILD
452/// /* but currently used for storing
453/// region-specific ITT */
454/// /* contextual information. */
455///#endif /* USE_ITT_BUILD */
456/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
457/// C++ */
458/// char const *psource; /**< String describing the source location.
459/// The string is composed of semi-colon separated
460// fields which describe the source file,
461/// the function and a pair of line numbers that
462/// delimit the construct.
463/// */
464/// } ident_t;
465enum IdentFieldIndex {
466 /// \brief might be used in Fortran
467 IdentField_Reserved_1,
468 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
469 IdentField_Flags,
470 /// \brief Not really used in Fortran any more
471 IdentField_Reserved_2,
472 /// \brief Source[4] in Fortran, do not use for C++
473 IdentField_Reserved_3,
474 /// \brief String describing the source location. The string is composed of
475 /// semi-colon separated fields which describe the source file, the function
476 /// and a pair of line numbers that delimit the construct.
477 IdentField_PSource
478};
479
480/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
481/// the enum sched_type in kmp.h).
482enum OpenMPSchedType {
483 /// \brief Lower bound for default (unordered) versions.
484 OMP_sch_lower = 32,
485 OMP_sch_static_chunked = 33,
486 OMP_sch_static = 34,
487 OMP_sch_dynamic_chunked = 35,
488 OMP_sch_guided_chunked = 36,
489 OMP_sch_runtime = 37,
490 OMP_sch_auto = 38,
491 /// \brief Lower bound for 'ordered' versions.
492 OMP_ord_lower = 64,
493 OMP_ord_static_chunked = 65,
494 OMP_ord_static = 66,
495 OMP_ord_dynamic_chunked = 67,
496 OMP_ord_guided_chunked = 68,
497 OMP_ord_runtime = 69,
498 OMP_ord_auto = 70,
499 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000500 /// \brief dist_schedule types
501 OMP_dist_sch_static_chunked = 91,
502 OMP_dist_sch_static = 92,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000503};
504
505enum OpenMPRTLFunction {
506 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
507 /// kmpc_micro microtask, ...);
508 OMPRTL__kmpc_fork_call,
509 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
510 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
511 OMPRTL__kmpc_threadprivate_cached,
512 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
513 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
514 OMPRTL__kmpc_threadprivate_register,
515 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
516 OMPRTL__kmpc_global_thread_num,
517 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
518 // kmp_critical_name *crit);
519 OMPRTL__kmpc_critical,
520 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
521 // global_tid, kmp_critical_name *crit, uintptr_t hint);
522 OMPRTL__kmpc_critical_with_hint,
523 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
524 // kmp_critical_name *crit);
525 OMPRTL__kmpc_end_critical,
526 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
527 // global_tid);
528 OMPRTL__kmpc_cancel_barrier,
529 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
530 OMPRTL__kmpc_barrier,
531 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
532 OMPRTL__kmpc_for_static_fini,
533 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
534 // global_tid);
535 OMPRTL__kmpc_serialized_parallel,
536 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
537 // global_tid);
538 OMPRTL__kmpc_end_serialized_parallel,
539 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
540 // kmp_int32 num_threads);
541 OMPRTL__kmpc_push_num_threads,
542 // Call to void __kmpc_flush(ident_t *loc);
543 OMPRTL__kmpc_flush,
544 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
545 OMPRTL__kmpc_master,
546 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
547 OMPRTL__kmpc_end_master,
548 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
549 // int end_part);
550 OMPRTL__kmpc_omp_taskyield,
551 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
552 OMPRTL__kmpc_single,
553 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
554 OMPRTL__kmpc_end_single,
555 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
556 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
557 // kmp_routine_entry_t *task_entry);
558 OMPRTL__kmpc_omp_task_alloc,
559 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
560 // new_task);
561 OMPRTL__kmpc_omp_task,
562 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
563 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
564 // kmp_int32 didit);
565 OMPRTL__kmpc_copyprivate,
566 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
567 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
568 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
569 OMPRTL__kmpc_reduce,
570 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
571 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
572 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
573 // *lck);
574 OMPRTL__kmpc_reduce_nowait,
575 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
576 // kmp_critical_name *lck);
577 OMPRTL__kmpc_end_reduce,
578 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
579 // kmp_critical_name *lck);
580 OMPRTL__kmpc_end_reduce_nowait,
581 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
582 // kmp_task_t * new_task);
583 OMPRTL__kmpc_omp_task_begin_if0,
584 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
585 // kmp_task_t * new_task);
586 OMPRTL__kmpc_omp_task_complete_if0,
587 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
588 OMPRTL__kmpc_ordered,
589 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
590 OMPRTL__kmpc_end_ordered,
591 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
592 // global_tid);
593 OMPRTL__kmpc_omp_taskwait,
594 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
595 OMPRTL__kmpc_taskgroup,
596 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
597 OMPRTL__kmpc_end_taskgroup,
598 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
599 // int proc_bind);
600 OMPRTL__kmpc_push_proc_bind,
601 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
602 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
603 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
604 OMPRTL__kmpc_omp_task_with_deps,
605 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
606 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
607 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
608 OMPRTL__kmpc_omp_wait_deps,
609 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
610 // global_tid, kmp_int32 cncl_kind);
611 OMPRTL__kmpc_cancellationpoint,
612 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
613 // kmp_int32 cncl_kind);
614 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000615 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
616 // kmp_int32 num_teams, kmp_int32 thread_limit);
617 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000618 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
619 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000620 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000621 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
622 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
623 // sched, kmp_uint64 grainsize, void *task_dup);
624 OMPRTL__kmpc_taskloop,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000625
626 //
627 // Offloading related calls
628 //
629 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
630 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
631 // *arg_types);
632 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000633 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
634 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
635 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
636 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000637 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
638 OMPRTL__tgt_register_lib,
639 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
640 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000641 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
642 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
643 OMPRTL__tgt_target_data_begin,
644 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
645 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
646 OMPRTL__tgt_target_data_end,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000647};
648
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000649/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
650/// region.
651class CleanupTy final : public EHScopeStack::Cleanup {
652 PrePostActionTy *Action;
653
654public:
655 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
656 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
657 if (!CGF.HaveInsertPoint())
658 return;
659 Action->Exit(CGF);
660 }
661};
662
Hans Wennborg7eb54642015-09-10 17:07:54 +0000663} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000664
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000665void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
666 CodeGenFunction::RunCleanupsScope Scope(CGF);
667 if (PrePostAction) {
668 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
669 Callback(CodeGen, CGF, *PrePostAction);
670 } else {
671 PrePostActionTy Action;
672 Callback(CodeGen, CGF, Action);
673 }
674}
675
Alexey Bataev18095712014-10-10 12:19:54 +0000676LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000677 return CGF.EmitLoadOfPointerLValue(
678 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
679 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000680}
681
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000682void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000683 if (!CGF.HaveInsertPoint())
684 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000685 // 1.2.2 OpenMP Language Terminology
686 // Structured block - An executable statement with a single entry at the
687 // top and a single exit at the bottom.
688 // The point of exit cannot be a branch out of the structured block.
689 // longjmp() and throw() must not violate the entry/exit criteria.
690 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000691 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000692 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000693}
694
Alexey Bataev62b63b12015-03-10 07:28:44 +0000695LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
696 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000697 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
698 getThreadIDVariable()->getType(),
699 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000700}
701
Alexey Bataev9959db52014-05-06 10:08:46 +0000702CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000703 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000704 IdentTy = llvm::StructType::create(
705 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
706 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000707 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000708 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000709
710 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000711}
712
Alexey Bataev91797552015-03-18 04:13:55 +0000713void CGOpenMPRuntime::clear() {
714 InternalVars.clear();
715}
716
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000717static llvm::Function *
718emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
719 const Expr *CombinerInitializer, const VarDecl *In,
720 const VarDecl *Out, bool IsCombiner) {
721 // void .omp_combiner.(Ty *in, Ty *out);
722 auto &C = CGM.getContext();
723 QualType PtrTy = C.getPointerType(Ty).withRestrict();
724 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000725 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
726 /*Id=*/nullptr, PtrTy);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000727 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
728 /*Id=*/nullptr, PtrTy);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000729 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000730 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000731 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000732 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000733 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
734 auto *Fn = llvm::Function::Create(
735 FnTy, llvm::GlobalValue::InternalLinkage,
736 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
737 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000738 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000739 CodeGenFunction CGF(CGM);
740 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
741 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
742 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
743 CodeGenFunction::OMPPrivateScope Scope(CGF);
744 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
745 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
746 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
747 .getAddress();
748 });
749 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
750 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
751 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
752 .getAddress();
753 });
754 (void)Scope.Privatize();
755 CGF.EmitIgnoredExpr(CombinerInitializer);
756 Scope.ForceCleanup();
757 CGF.FinishFunction();
758 return Fn;
759}
760
761void CGOpenMPRuntime::emitUserDefinedReduction(
762 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
763 if (UDRMap.count(D) > 0)
764 return;
765 auto &C = CGM.getContext();
766 if (!In || !Out) {
767 In = &C.Idents.get("omp_in");
768 Out = &C.Idents.get("omp_out");
769 }
770 llvm::Function *Combiner = emitCombinerOrInitializer(
771 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
772 cast<VarDecl>(D->lookup(Out).front()),
773 /*IsCombiner=*/true);
774 llvm::Function *Initializer = nullptr;
775 if (auto *Init = D->getInitializer()) {
776 if (!Priv || !Orig) {
777 Priv = &C.Idents.get("omp_priv");
778 Orig = &C.Idents.get("omp_orig");
779 }
780 Initializer = emitCombinerOrInitializer(
781 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
782 cast<VarDecl>(D->lookup(Priv).front()),
783 /*IsCombiner=*/false);
784 }
785 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
786 if (CGF) {
787 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
788 Decls.second.push_back(D);
789 }
790}
791
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000792std::pair<llvm::Function *, llvm::Function *>
793CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
794 auto I = UDRMap.find(D);
795 if (I != UDRMap.end())
796 return I->second;
797 emitUserDefinedReduction(/*CGF=*/nullptr, D);
798 return UDRMap.lookup(D);
799}
800
John McCall7f416cc2015-09-08 08:05:57 +0000801// Layout information for ident_t.
802static CharUnits getIdentAlign(CodeGenModule &CGM) {
803 return CGM.getPointerAlign();
804}
805static CharUnits getIdentSize(CodeGenModule &CGM) {
806 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
807 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
808}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000809static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000810 // All the fields except the last are i32, so this works beautifully.
811 return unsigned(Field) * CharUnits::fromQuantity(4);
812}
813static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000814 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000815 const llvm::Twine &Name = "") {
816 auto Offset = getOffsetOfIdentField(Field);
817 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
818}
819
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000820llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000821 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
822 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000823 assert(ThreadIDVar->getType()->isPointerType() &&
824 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000825 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
826 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000827 bool HasCancel = false;
828 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
829 HasCancel = OPD->hasCancel();
830 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
831 HasCancel = OPSD->hasCancel();
832 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
833 HasCancel = OPFD->hasCancel();
834 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
835 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000836 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000837 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000838}
839
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000840llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
841 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000842 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
843 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
844 bool Tied, unsigned &NumberOfParts) {
845 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
846 PrePostActionTy &) {
847 auto *ThreadID = getThreadID(CGF, D.getLocStart());
848 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
849 llvm::Value *TaskArgs[] = {
850 UpLoc, ThreadID,
851 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
852 TaskTVar->getType()->castAs<PointerType>())
853 .getPointer()};
854 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
855 };
856 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
857 UntiedCodeGen);
858 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000859 assert(!ThreadIDVar->getType()->isPointerType() &&
860 "thread id variable must be of type kmp_int32 for tasks");
861 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +0000862 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000863 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +0000864 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
865 InnermostKind,
866 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +0000867 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +0000868 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
869 if (!Tied)
870 NumberOfParts = Action.getNumberOfParts();
871 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000872}
873
Alexey Bataev50b3c952016-02-19 10:38:26 +0000874Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000875 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000876 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000877 if (!Entry) {
878 if (!DefaultOpenMPPSource) {
879 // Initialize default location for psource field of ident_t structure of
880 // all ident_t objects. Format is ";file;function;line;column;;".
881 // Taken from
882 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
883 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000884 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000885 DefaultOpenMPPSource =
886 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
887 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000888 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
889 CGM.getModule(), IdentTy, /*isConstant*/ true,
890 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000891 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000892 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000893
894 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000895 llvm::Constant *Values[] = {Zero,
896 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
897 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000898 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
899 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000900 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000901 }
John McCall7f416cc2015-09-08 08:05:57 +0000902 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000903}
904
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000905llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
906 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000907 unsigned Flags) {
908 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000909 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000910 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000911 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000912 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000913
914 assert(CGF.CurFn && "No function in current CodeGenFunction.");
915
John McCall7f416cc2015-09-08 08:05:57 +0000916 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000917 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
918 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000919 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
920
Alexander Musmanc6388682014-12-15 07:07:06 +0000921 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
922 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000923 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000924 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000925 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
926 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000927 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000928 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000929 LocValue = AI;
930
931 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
932 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000933 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000934 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000935 }
936
937 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000938 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000939
Alexey Bataevf002aca2014-05-30 05:48:40 +0000940 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
941 if (OMPDebugLoc == nullptr) {
942 SmallString<128> Buffer2;
943 llvm::raw_svector_ostream OS2(Buffer2);
944 // Build debug location
945 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
946 OS2 << ";" << PLoc.getFilename() << ";";
947 if (const FunctionDecl *FD =
948 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
949 OS2 << FD->getQualifiedNameAsString();
950 }
951 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
952 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
953 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000954 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000955 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000956 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
957
John McCall7f416cc2015-09-08 08:05:57 +0000958 // Our callers always pass this to a runtime function, so for
959 // convenience, go ahead and return a naked pointer.
960 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000961}
962
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000963llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
964 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000965 assert(CGF.CurFn && "No function in current CodeGenFunction.");
966
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000967 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000968 // Check whether we've already cached a load of the thread id in this
969 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000970 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000971 if (I != OpenMPLocThreadIDMap.end()) {
972 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000973 if (ThreadID != nullptr)
974 return ThreadID;
975 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000976 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000977 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000978 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000979 // Check if this an outlined function with thread id passed as argument.
980 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000981 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
982 // If value loaded in entry block, cache it and use it everywhere in
983 // function.
984 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
985 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
986 Elem.second.ThreadID = ThreadID;
987 }
988 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000989 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000990 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000991
992 // This is not an outlined function region - need to call __kmpc_int32
993 // kmpc_global_thread_num(ident_t *loc).
994 // Generate thread id value and cache this value for use across the
995 // function.
996 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
997 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
998 ThreadID =
999 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1000 emitUpdateLocation(CGF, Loc));
1001 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1002 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001003 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001004}
1005
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001006void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001007 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001008 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1009 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001010 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1011 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1012 UDRMap.erase(D);
1013 }
1014 FunctionUDRMap.erase(CGF.CurFn);
1015 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001016}
1017
1018llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001019 if (!IdentTy) {
1020 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001021 return llvm::PointerType::getUnqual(IdentTy);
1022}
1023
1024llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001025 if (!Kmpc_MicroTy) {
1026 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1027 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1028 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1029 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1030 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001031 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1032}
1033
1034llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001035CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001036 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001037 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001038 case OMPRTL__kmpc_fork_call: {
1039 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1040 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001041 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1042 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001043 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001044 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001045 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1046 break;
1047 }
1048 case OMPRTL__kmpc_global_thread_num: {
1049 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001050 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001051 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001052 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001053 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1054 break;
1055 }
Alexey Bataev97720002014-11-11 04:05:39 +00001056 case OMPRTL__kmpc_threadprivate_cached: {
1057 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1058 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1059 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1060 CGM.VoidPtrTy, CGM.SizeTy,
1061 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1062 llvm::FunctionType *FnTy =
1063 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1064 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1065 break;
1066 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001067 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001068 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1069 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001070 llvm::Type *TypeParams[] = {
1071 getIdentTyPointerTy(), CGM.Int32Ty,
1072 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1073 llvm::FunctionType *FnTy =
1074 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1075 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1076 break;
1077 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001078 case OMPRTL__kmpc_critical_with_hint: {
1079 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1080 // kmp_critical_name *crit, uintptr_t hint);
1081 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1082 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1083 CGM.IntPtrTy};
1084 llvm::FunctionType *FnTy =
1085 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1086 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1087 break;
1088 }
Alexey Bataev97720002014-11-11 04:05:39 +00001089 case OMPRTL__kmpc_threadprivate_register: {
1090 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1091 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1092 // typedef void *(*kmpc_ctor)(void *);
1093 auto KmpcCtorTy =
1094 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1095 /*isVarArg*/ false)->getPointerTo();
1096 // typedef void *(*kmpc_cctor)(void *, void *);
1097 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1098 auto KmpcCopyCtorTy =
1099 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1100 /*isVarArg*/ false)->getPointerTo();
1101 // typedef void (*kmpc_dtor)(void *);
1102 auto KmpcDtorTy =
1103 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1104 ->getPointerTo();
1105 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1106 KmpcCopyCtorTy, KmpcDtorTy};
1107 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1108 /*isVarArg*/ false);
1109 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1110 break;
1111 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001112 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001113 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1114 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001115 llvm::Type *TypeParams[] = {
1116 getIdentTyPointerTy(), CGM.Int32Ty,
1117 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1118 llvm::FunctionType *FnTy =
1119 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1120 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1121 break;
1122 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001123 case OMPRTL__kmpc_cancel_barrier: {
1124 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1125 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001126 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1127 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001128 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1129 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001130 break;
1131 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001132 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001133 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001134 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1135 llvm::FunctionType *FnTy =
1136 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1137 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1138 break;
1139 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001140 case OMPRTL__kmpc_for_static_fini: {
1141 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1142 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1143 llvm::FunctionType *FnTy =
1144 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1145 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1146 break;
1147 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001148 case OMPRTL__kmpc_push_num_threads: {
1149 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1150 // kmp_int32 num_threads)
1151 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1152 CGM.Int32Ty};
1153 llvm::FunctionType *FnTy =
1154 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1155 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1156 break;
1157 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001158 case OMPRTL__kmpc_serialized_parallel: {
1159 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1160 // global_tid);
1161 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1162 llvm::FunctionType *FnTy =
1163 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1164 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1165 break;
1166 }
1167 case OMPRTL__kmpc_end_serialized_parallel: {
1168 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1169 // global_tid);
1170 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1171 llvm::FunctionType *FnTy =
1172 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1173 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1174 break;
1175 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001176 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001177 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001178 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1179 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001180 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001181 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1182 break;
1183 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001184 case OMPRTL__kmpc_master: {
1185 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1186 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1187 llvm::FunctionType *FnTy =
1188 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1189 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1190 break;
1191 }
1192 case OMPRTL__kmpc_end_master: {
1193 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1194 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1195 llvm::FunctionType *FnTy =
1196 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1197 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1198 break;
1199 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001200 case OMPRTL__kmpc_omp_taskyield: {
1201 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1202 // int end_part);
1203 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1204 llvm::FunctionType *FnTy =
1205 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1206 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1207 break;
1208 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001209 case OMPRTL__kmpc_single: {
1210 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1211 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1212 llvm::FunctionType *FnTy =
1213 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1214 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1215 break;
1216 }
1217 case OMPRTL__kmpc_end_single: {
1218 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1219 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1220 llvm::FunctionType *FnTy =
1221 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1222 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1223 break;
1224 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001225 case OMPRTL__kmpc_omp_task_alloc: {
1226 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1227 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1228 // kmp_routine_entry_t *task_entry);
1229 assert(KmpRoutineEntryPtrTy != nullptr &&
1230 "Type kmp_routine_entry_t must be created.");
1231 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1232 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1233 // Return void * and then cast to particular kmp_task_t type.
1234 llvm::FunctionType *FnTy =
1235 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1236 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1237 break;
1238 }
1239 case OMPRTL__kmpc_omp_task: {
1240 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1241 // *new_task);
1242 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1243 CGM.VoidPtrTy};
1244 llvm::FunctionType *FnTy =
1245 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1246 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1247 break;
1248 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001249 case OMPRTL__kmpc_copyprivate: {
1250 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001251 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001252 // kmp_int32 didit);
1253 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1254 auto *CpyFnTy =
1255 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001256 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001257 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1258 CGM.Int32Ty};
1259 llvm::FunctionType *FnTy =
1260 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1261 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1262 break;
1263 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001264 case OMPRTL__kmpc_reduce: {
1265 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1266 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1267 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1268 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1269 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1270 /*isVarArg=*/false);
1271 llvm::Type *TypeParams[] = {
1272 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1273 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1274 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1275 llvm::FunctionType *FnTy =
1276 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1277 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1278 break;
1279 }
1280 case OMPRTL__kmpc_reduce_nowait: {
1281 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1282 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1283 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1284 // *lck);
1285 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1286 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1287 /*isVarArg=*/false);
1288 llvm::Type *TypeParams[] = {
1289 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1290 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1291 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1292 llvm::FunctionType *FnTy =
1293 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1294 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1295 break;
1296 }
1297 case OMPRTL__kmpc_end_reduce: {
1298 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1299 // kmp_critical_name *lck);
1300 llvm::Type *TypeParams[] = {
1301 getIdentTyPointerTy(), CGM.Int32Ty,
1302 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1303 llvm::FunctionType *FnTy =
1304 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1305 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1306 break;
1307 }
1308 case OMPRTL__kmpc_end_reduce_nowait: {
1309 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1310 // kmp_critical_name *lck);
1311 llvm::Type *TypeParams[] = {
1312 getIdentTyPointerTy(), CGM.Int32Ty,
1313 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1314 llvm::FunctionType *FnTy =
1315 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1316 RTLFn =
1317 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1318 break;
1319 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001320 case OMPRTL__kmpc_omp_task_begin_if0: {
1321 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1322 // *new_task);
1323 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1324 CGM.VoidPtrTy};
1325 llvm::FunctionType *FnTy =
1326 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1327 RTLFn =
1328 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1329 break;
1330 }
1331 case OMPRTL__kmpc_omp_task_complete_if0: {
1332 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1333 // *new_task);
1334 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1335 CGM.VoidPtrTy};
1336 llvm::FunctionType *FnTy =
1337 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1338 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1339 /*Name=*/"__kmpc_omp_task_complete_if0");
1340 break;
1341 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001342 case OMPRTL__kmpc_ordered: {
1343 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1344 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1345 llvm::FunctionType *FnTy =
1346 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1347 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1348 break;
1349 }
1350 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001351 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001352 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1353 llvm::FunctionType *FnTy =
1354 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1355 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1356 break;
1357 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001358 case OMPRTL__kmpc_omp_taskwait: {
1359 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1360 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1361 llvm::FunctionType *FnTy =
1362 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1363 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1364 break;
1365 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001366 case OMPRTL__kmpc_taskgroup: {
1367 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1368 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1369 llvm::FunctionType *FnTy =
1370 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1371 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1372 break;
1373 }
1374 case OMPRTL__kmpc_end_taskgroup: {
1375 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1376 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1377 llvm::FunctionType *FnTy =
1378 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1379 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1380 break;
1381 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001382 case OMPRTL__kmpc_push_proc_bind: {
1383 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1384 // int proc_bind)
1385 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1386 llvm::FunctionType *FnTy =
1387 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1388 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1389 break;
1390 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001391 case OMPRTL__kmpc_omp_task_with_deps: {
1392 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1393 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1394 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1395 llvm::Type *TypeParams[] = {
1396 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1397 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1398 llvm::FunctionType *FnTy =
1399 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1400 RTLFn =
1401 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1402 break;
1403 }
1404 case OMPRTL__kmpc_omp_wait_deps: {
1405 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1406 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1407 // kmp_depend_info_t *noalias_dep_list);
1408 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1409 CGM.Int32Ty, CGM.VoidPtrTy,
1410 CGM.Int32Ty, CGM.VoidPtrTy};
1411 llvm::FunctionType *FnTy =
1412 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1413 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1414 break;
1415 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001416 case OMPRTL__kmpc_cancellationpoint: {
1417 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1418 // global_tid, kmp_int32 cncl_kind)
1419 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1420 llvm::FunctionType *FnTy =
1421 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1422 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1423 break;
1424 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001425 case OMPRTL__kmpc_cancel: {
1426 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1427 // kmp_int32 cncl_kind)
1428 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1429 llvm::FunctionType *FnTy =
1430 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1431 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1432 break;
1433 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001434 case OMPRTL__kmpc_push_num_teams: {
1435 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1436 // kmp_int32 num_teams, kmp_int32 num_threads)
1437 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1438 CGM.Int32Ty};
1439 llvm::FunctionType *FnTy =
1440 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1441 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1442 break;
1443 }
1444 case OMPRTL__kmpc_fork_teams: {
1445 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1446 // microtask, ...);
1447 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1448 getKmpc_MicroPointerTy()};
1449 llvm::FunctionType *FnTy =
1450 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1451 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1452 break;
1453 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001454 case OMPRTL__kmpc_taskloop: {
1455 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1456 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1457 // sched, kmp_uint64 grainsize, void *task_dup);
1458 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1459 CGM.IntTy,
1460 CGM.VoidPtrTy,
1461 CGM.IntTy,
1462 CGM.Int64Ty->getPointerTo(),
1463 CGM.Int64Ty->getPointerTo(),
1464 CGM.Int64Ty,
1465 CGM.IntTy,
1466 CGM.IntTy,
1467 CGM.Int64Ty,
1468 CGM.VoidPtrTy};
1469 llvm::FunctionType *FnTy =
1470 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1471 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1472 break;
1473 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001474 case OMPRTL__tgt_target: {
1475 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1476 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1477 // *arg_types);
1478 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1479 CGM.VoidPtrTy,
1480 CGM.Int32Ty,
1481 CGM.VoidPtrPtrTy,
1482 CGM.VoidPtrPtrTy,
1483 CGM.SizeTy->getPointerTo(),
1484 CGM.Int32Ty->getPointerTo()};
1485 llvm::FunctionType *FnTy =
1486 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1487 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1488 break;
1489 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001490 case OMPRTL__tgt_target_teams: {
1491 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1492 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1493 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1494 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1495 CGM.VoidPtrTy,
1496 CGM.Int32Ty,
1497 CGM.VoidPtrPtrTy,
1498 CGM.VoidPtrPtrTy,
1499 CGM.SizeTy->getPointerTo(),
1500 CGM.Int32Ty->getPointerTo(),
1501 CGM.Int32Ty,
1502 CGM.Int32Ty};
1503 llvm::FunctionType *FnTy =
1504 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1505 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1506 break;
1507 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001508 case OMPRTL__tgt_register_lib: {
1509 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1510 QualType ParamTy =
1511 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1512 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1513 llvm::FunctionType *FnTy =
1514 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1515 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1516 break;
1517 }
1518 case OMPRTL__tgt_unregister_lib: {
1519 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1520 QualType ParamTy =
1521 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1522 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1523 llvm::FunctionType *FnTy =
1524 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1525 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1526 break;
1527 }
Samuel Antaodf158d52016-04-27 22:58:19 +00001528 case OMPRTL__tgt_target_data_begin: {
1529 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1530 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1531 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1532 CGM.Int32Ty,
1533 CGM.VoidPtrPtrTy,
1534 CGM.VoidPtrPtrTy,
1535 CGM.SizeTy->getPointerTo(),
1536 CGM.Int32Ty->getPointerTo()};
1537 llvm::FunctionType *FnTy =
1538 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1539 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1540 break;
1541 }
1542 case OMPRTL__tgt_target_data_end: {
1543 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1544 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1545 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1546 CGM.Int32Ty,
1547 CGM.VoidPtrPtrTy,
1548 CGM.VoidPtrPtrTy,
1549 CGM.SizeTy->getPointerTo(),
1550 CGM.Int32Ty->getPointerTo()};
1551 llvm::FunctionType *FnTy =
1552 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1553 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1554 break;
1555 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001556 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001557 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001558 return RTLFn;
1559}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001560
Alexander Musman21212e42015-03-13 10:38:23 +00001561llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1562 bool IVSigned) {
1563 assert((IVSize == 32 || IVSize == 64) &&
1564 "IV size is not compatible with the omp runtime");
1565 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1566 : "__kmpc_for_static_init_4u")
1567 : (IVSigned ? "__kmpc_for_static_init_8"
1568 : "__kmpc_for_static_init_8u");
1569 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1570 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1571 llvm::Type *TypeParams[] = {
1572 getIdentTyPointerTy(), // loc
1573 CGM.Int32Ty, // tid
1574 CGM.Int32Ty, // schedtype
1575 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1576 PtrTy, // p_lower
1577 PtrTy, // p_upper
1578 PtrTy, // p_stride
1579 ITy, // incr
1580 ITy // chunk
1581 };
1582 llvm::FunctionType *FnTy =
1583 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1584 return CGM.CreateRuntimeFunction(FnTy, Name);
1585}
1586
Alexander Musman92bdaab2015-03-12 13:37:50 +00001587llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1588 bool IVSigned) {
1589 assert((IVSize == 32 || IVSize == 64) &&
1590 "IV size is not compatible with the omp runtime");
1591 auto Name =
1592 IVSize == 32
1593 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1594 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1595 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1596 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1597 CGM.Int32Ty, // tid
1598 CGM.Int32Ty, // schedtype
1599 ITy, // lower
1600 ITy, // upper
1601 ITy, // stride
1602 ITy // chunk
1603 };
1604 llvm::FunctionType *FnTy =
1605 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1606 return CGM.CreateRuntimeFunction(FnTy, Name);
1607}
1608
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001609llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1610 bool IVSigned) {
1611 assert((IVSize == 32 || IVSize == 64) &&
1612 "IV size is not compatible with the omp runtime");
1613 auto Name =
1614 IVSize == 32
1615 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1616 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1617 llvm::Type *TypeParams[] = {
1618 getIdentTyPointerTy(), // loc
1619 CGM.Int32Ty, // tid
1620 };
1621 llvm::FunctionType *FnTy =
1622 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1623 return CGM.CreateRuntimeFunction(FnTy, Name);
1624}
1625
Alexander Musman92bdaab2015-03-12 13:37:50 +00001626llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1627 bool IVSigned) {
1628 assert((IVSize == 32 || IVSize == 64) &&
1629 "IV size is not compatible with the omp runtime");
1630 auto Name =
1631 IVSize == 32
1632 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1633 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1634 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1635 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1636 llvm::Type *TypeParams[] = {
1637 getIdentTyPointerTy(), // loc
1638 CGM.Int32Ty, // tid
1639 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1640 PtrTy, // p_lower
1641 PtrTy, // p_upper
1642 PtrTy // p_stride
1643 };
1644 llvm::FunctionType *FnTy =
1645 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1646 return CGM.CreateRuntimeFunction(FnTy, Name);
1647}
1648
Alexey Bataev97720002014-11-11 04:05:39 +00001649llvm::Constant *
1650CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001651 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1652 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001653 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001654 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001655 Twine(CGM.getMangledName(VD)) + ".cache.");
1656}
1657
John McCall7f416cc2015-09-08 08:05:57 +00001658Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1659 const VarDecl *VD,
1660 Address VDAddr,
1661 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001662 if (CGM.getLangOpts().OpenMPUseTLS &&
1663 CGM.getContext().getTargetInfo().isTLSSupported())
1664 return VDAddr;
1665
John McCall7f416cc2015-09-08 08:05:57 +00001666 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001667 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001668 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1669 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001670 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1671 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001672 return Address(CGF.EmitRuntimeCall(
1673 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1674 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001675}
1676
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001677void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001678 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001679 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1680 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1681 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001682 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1683 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001684 OMPLoc);
1685 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1686 // to register constructor/destructor for variable.
1687 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001688 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1689 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001690 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001691 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001692 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001693}
1694
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001695llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001696 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001697 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001698 if (CGM.getLangOpts().OpenMPUseTLS &&
1699 CGM.getContext().getTargetInfo().isTLSSupported())
1700 return nullptr;
1701
Alexey Bataev97720002014-11-11 04:05:39 +00001702 VD = VD->getDefinition(CGM.getContext());
1703 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1704 ThreadPrivateWithDefinition.insert(VD);
1705 QualType ASTTy = VD->getType();
1706
1707 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1708 auto Init = VD->getAnyInitializer();
1709 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1710 // Generate function that re-emits the declaration's initializer into the
1711 // threadprivate copy of the variable VD
1712 CodeGenFunction CtorCGF(CGM);
1713 FunctionArgList Args;
1714 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1715 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1716 Args.push_back(&Dst);
1717
John McCallc56a8b32016-03-11 04:30:31 +00001718 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1719 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001720 auto FTy = CGM.getTypes().GetFunctionType(FI);
1721 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001722 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001723 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1724 Args, SourceLocation());
1725 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001726 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001727 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001728 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1729 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1730 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001731 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1732 /*IsInitializer=*/true);
1733 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001734 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001735 CGM.getContext().VoidPtrTy, Dst.getLocation());
1736 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1737 CtorCGF.FinishFunction();
1738 Ctor = Fn;
1739 }
1740 if (VD->getType().isDestructedType() != QualType::DK_none) {
1741 // Generate function that emits destructor call for the threadprivate copy
1742 // of the variable VD
1743 CodeGenFunction DtorCGF(CGM);
1744 FunctionArgList Args;
1745 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1746 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1747 Args.push_back(&Dst);
1748
John McCallc56a8b32016-03-11 04:30:31 +00001749 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1750 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001751 auto FTy = CGM.getTypes().GetFunctionType(FI);
1752 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001753 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00001754 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001755 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1756 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00001757 // Create a scope with an artificial location for the body of this function.
1758 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001759 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1760 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001761 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1762 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001763 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1764 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1765 DtorCGF.FinishFunction();
1766 Dtor = Fn;
1767 }
1768 // Do not emit init function if it is not required.
1769 if (!Ctor && !Dtor)
1770 return nullptr;
1771
1772 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1773 auto CopyCtorTy =
1774 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1775 /*isVarArg=*/false)->getPointerTo();
1776 // Copying constructor for the threadprivate variable.
1777 // Must be NULL - reserved by runtime, but currently it requires that this
1778 // parameter is always NULL. Otherwise it fires assertion.
1779 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1780 if (Ctor == nullptr) {
1781 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1782 /*isVarArg=*/false)->getPointerTo();
1783 Ctor = llvm::Constant::getNullValue(CtorTy);
1784 }
1785 if (Dtor == nullptr) {
1786 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1787 /*isVarArg=*/false)->getPointerTo();
1788 Dtor = llvm::Constant::getNullValue(DtorTy);
1789 }
1790 if (!CGF) {
1791 auto InitFunctionTy =
1792 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1793 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001794 InitFunctionTy, ".__omp_threadprivate_init_.",
1795 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001796 CodeGenFunction InitCGF(CGM);
1797 FunctionArgList ArgList;
1798 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1799 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1800 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001801 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001802 InitCGF.FinishFunction();
1803 return InitFunction;
1804 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001805 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001806 }
1807 return nullptr;
1808}
1809
Alexey Bataev1d677132015-04-22 13:57:31 +00001810/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1811/// function. Here is the logic:
1812/// if (Cond) {
1813/// ThenGen();
1814/// } else {
1815/// ElseGen();
1816/// }
1817static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1818 const RegionCodeGenTy &ThenGen,
1819 const RegionCodeGenTy &ElseGen) {
1820 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1821
1822 // If the condition constant folds and can be elided, try to avoid emitting
1823 // the condition and the dead arm of the if/else.
1824 bool CondConstant;
1825 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001826 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001827 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001828 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001829 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001830 return;
1831 }
1832
1833 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1834 // emit the conditional branch.
1835 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1836 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1837 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1838 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1839
1840 // Emit the 'then' code.
1841 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001842 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001843 CGF.EmitBranch(ContBlock);
1844 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001845 // There is no need to emit line number for unconditional branch.
1846 (void)ApplyDebugLocation::CreateEmpty(CGF);
1847 CGF.EmitBlock(ElseBlock);
1848 ElseGen(CGF);
1849 // There is no need to emit line number for unconditional branch.
1850 (void)ApplyDebugLocation::CreateEmpty(CGF);
1851 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001852 // Emit the continuation block for code after the if.
1853 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001854}
1855
Alexey Bataev1d677132015-04-22 13:57:31 +00001856void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1857 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001858 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001859 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001860 if (!CGF.HaveInsertPoint())
1861 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001862 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001863 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1864 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001865 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001866 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001867 llvm::Value *Args[] = {
1868 RTLoc,
1869 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001870 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001871 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1872 RealArgs.append(std::begin(Args), std::end(Args));
1873 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1874
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001875 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001876 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1877 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001878 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1879 PrePostActionTy &) {
1880 auto &RT = CGF.CGM.getOpenMPRuntime();
1881 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001882 // Build calls:
1883 // __kmpc_serialized_parallel(&Loc, GTid);
1884 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001885 CGF.EmitRuntimeCall(
1886 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001887
Alexey Bataev1d677132015-04-22 13:57:31 +00001888 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001889 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001890 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001891 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1892 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001893 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001894 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1895 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1896 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1897 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001898 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001899
Alexey Bataev1d677132015-04-22 13:57:31 +00001900 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001901 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001902 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001903 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
1904 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00001905 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001906 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00001907 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001908 else {
1909 RegionCodeGenTy ThenRCG(ThenGen);
1910 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00001911 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001912}
1913
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001914// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001915// thread-ID variable (it is passed in a first argument of the outlined function
1916// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1917// regular serial code region, get thread ID by calling kmp_int32
1918// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1919// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001920Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1921 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001922 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001923 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001924 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001925 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001926
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001927 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001928 auto Int32Ty =
1929 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1930 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1931 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001932 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001933
1934 return ThreadIDTemp;
1935}
1936
Alexey Bataev97720002014-11-11 04:05:39 +00001937llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001938CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001939 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001940 SmallString<256> Buffer;
1941 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001942 Out << Name;
1943 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001944 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1945 if (Elem.second) {
1946 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001947 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001948 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001949 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001950
David Blaikie13156b62014-11-19 03:06:06 +00001951 return Elem.second = new llvm::GlobalVariable(
1952 CGM.getModule(), Ty, /*IsConstant*/ false,
1953 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1954 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001955}
1956
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001957llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001958 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001959 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001960}
1961
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001962namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001963/// Common pre(post)-action for different OpenMP constructs.
1964class CommonActionTy final : public PrePostActionTy {
1965 llvm::Value *EnterCallee;
1966 ArrayRef<llvm::Value *> EnterArgs;
1967 llvm::Value *ExitCallee;
1968 ArrayRef<llvm::Value *> ExitArgs;
1969 bool Conditional;
1970 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001971
1972public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001973 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
1974 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
1975 bool Conditional = false)
1976 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
1977 ExitArgs(ExitArgs), Conditional(Conditional) {}
1978 void Enter(CodeGenFunction &CGF) override {
1979 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
1980 if (Conditional) {
1981 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
1982 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1983 ContBlock = CGF.createBasicBlock("omp_if.end");
1984 // Generate the branch (If-stmt)
1985 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1986 CGF.EmitBlock(ThenBlock);
1987 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00001988 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001989 void Done(CodeGenFunction &CGF) {
1990 // Emit the rest of blocks/branches
1991 CGF.EmitBranch(ContBlock);
1992 CGF.EmitBlock(ContBlock, true);
1993 }
1994 void Exit(CodeGenFunction &CGF) override {
1995 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001996 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001997};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001998} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001999
2000void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2001 StringRef CriticalName,
2002 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002003 SourceLocation Loc, const Expr *Hint) {
2004 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002005 // CriticalOpGen();
2006 // __kmpc_end_critical(ident_t *, gtid, Lock);
2007 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002008 if (!CGF.HaveInsertPoint())
2009 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002010 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2011 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002012 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2013 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002014 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002015 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2016 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2017 }
2018 CommonActionTy Action(
2019 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2020 : OMPRTL__kmpc_critical),
2021 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2022 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002023 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002024}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002025
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002026void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002027 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002028 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002029 if (!CGF.HaveInsertPoint())
2030 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002031 // if(__kmpc_master(ident_t *, gtid)) {
2032 // MasterOpGen();
2033 // __kmpc_end_master(ident_t *, gtid);
2034 // }
2035 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002036 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002037 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2038 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2039 /*Conditional=*/true);
2040 MasterOpGen.setAction(Action);
2041 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2042 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002043}
2044
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002045void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2046 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002047 if (!CGF.HaveInsertPoint())
2048 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002049 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2050 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002051 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002052 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002053 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002054 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2055 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002056}
2057
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002058void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2059 const RegionCodeGenTy &TaskgroupOpGen,
2060 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002061 if (!CGF.HaveInsertPoint())
2062 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002063 // __kmpc_taskgroup(ident_t *, gtid);
2064 // TaskgroupOpGen();
2065 // __kmpc_end_taskgroup(ident_t *, gtid);
2066 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002067 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2068 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2069 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2070 Args);
2071 TaskgroupOpGen.setAction(Action);
2072 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002073}
2074
John McCall7f416cc2015-09-08 08:05:57 +00002075/// Given an array of pointers to variables, project the address of a
2076/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002077static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2078 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002079 // Pull out the pointer to the variable.
2080 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002081 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002082 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2083
2084 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002085 Addr = CGF.Builder.CreateElementBitCast(
2086 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002087 return Addr;
2088}
2089
Alexey Bataeva63048e2015-03-23 06:18:07 +00002090static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002091 CodeGenModule &CGM, llvm::Type *ArgsType,
2092 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2093 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002094 auto &C = CGM.getContext();
2095 // void copy_func(void *LHSArg, void *RHSArg);
2096 FunctionArgList Args;
2097 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2098 C.VoidPtrTy);
2099 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2100 C.VoidPtrTy);
2101 Args.push_back(&LHSArg);
2102 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002103 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002104 auto *Fn = llvm::Function::Create(
2105 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2106 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002107 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002108 CodeGenFunction CGF(CGM);
2109 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002110 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002111 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002112 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2113 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2114 ArgsType), CGF.getPointerAlign());
2115 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2116 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2117 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002118 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2119 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2120 // ...
2121 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002122 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002123 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2124 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2125
2126 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2127 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2128
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002129 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2130 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002131 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002132 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002133 CGF.FinishFunction();
2134 return Fn;
2135}
2136
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002137void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002138 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002139 SourceLocation Loc,
2140 ArrayRef<const Expr *> CopyprivateVars,
2141 ArrayRef<const Expr *> SrcExprs,
2142 ArrayRef<const Expr *> DstExprs,
2143 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002144 if (!CGF.HaveInsertPoint())
2145 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002146 assert(CopyprivateVars.size() == SrcExprs.size() &&
2147 CopyprivateVars.size() == DstExprs.size() &&
2148 CopyprivateVars.size() == AssignmentOps.size());
2149 auto &C = CGM.getContext();
2150 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002151 // if(__kmpc_single(ident_t *, gtid)) {
2152 // SingleOpGen();
2153 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002154 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002155 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002156 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2157 // <copy_func>, did_it);
2158
John McCall7f416cc2015-09-08 08:05:57 +00002159 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002160 if (!CopyprivateVars.empty()) {
2161 // int32 did_it = 0;
2162 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2163 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002164 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002165 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002166 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002167 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002168 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2169 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2170 /*Conditional=*/true);
2171 SingleOpGen.setAction(Action);
2172 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2173 if (DidIt.isValid()) {
2174 // did_it = 1;
2175 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2176 }
2177 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002178 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2179 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002180 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002181 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2182 auto CopyprivateArrayTy =
2183 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2184 /*IndexTypeQuals=*/0);
2185 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002186 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002187 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2188 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002189 Address Elem = CGF.Builder.CreateConstArrayGEP(
2190 CopyprivateList, I, CGF.getPointerSize());
2191 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002192 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002193 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2194 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002195 }
2196 // Build function that copies private values from single region to all other
2197 // threads in the corresponding parallel region.
2198 auto *CpyFn = emitCopyprivateCopyFunction(
2199 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002200 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002201 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002202 Address CL =
2203 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2204 CGF.VoidPtrTy);
2205 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002206 llvm::Value *Args[] = {
2207 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2208 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002209 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002210 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002211 CpyFn, // void (*) (void *, void *) <copy_func>
2212 DidItVal // i32 did_it
2213 };
2214 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2215 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002216}
2217
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002218void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2219 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002220 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002221 if (!CGF.HaveInsertPoint())
2222 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002223 // __kmpc_ordered(ident_t *, gtid);
2224 // OrderedOpGen();
2225 // __kmpc_end_ordered(ident_t *, gtid);
2226 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002227 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002228 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002229 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2230 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2231 Args);
2232 OrderedOpGen.setAction(Action);
2233 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2234 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002235 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002236 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002237}
2238
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002239void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002240 OpenMPDirectiveKind Kind, bool EmitChecks,
2241 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002242 if (!CGF.HaveInsertPoint())
2243 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002244 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002245 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002246 unsigned Flags;
2247 if (Kind == OMPD_for)
2248 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2249 else if (Kind == OMPD_sections)
2250 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2251 else if (Kind == OMPD_single)
2252 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2253 else if (Kind == OMPD_barrier)
2254 Flags = OMP_IDENT_BARRIER_EXPL;
2255 else
2256 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002257 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2258 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002259 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2260 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002261 if (auto *OMPRegionInfo =
2262 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002263 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002264 auto *Result = CGF.EmitRuntimeCall(
2265 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002266 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002267 // if (__kmpc_cancel_barrier()) {
2268 // exit from construct;
2269 // }
2270 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2271 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2272 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2273 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2274 CGF.EmitBlock(ExitBB);
2275 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002276 auto CancelDestination =
2277 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002278 CGF.EmitBranchThroughCleanup(CancelDestination);
2279 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2280 }
2281 return;
2282 }
2283 }
2284 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002285}
2286
Alexander Musmanc6388682014-12-15 07:07:06 +00002287/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2288static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002289 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002290 switch (ScheduleKind) {
2291 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002292 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2293 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002294 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002295 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002296 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002297 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002298 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002299 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2300 case OMPC_SCHEDULE_auto:
2301 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002302 case OMPC_SCHEDULE_unknown:
2303 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002304 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002305 }
2306 llvm_unreachable("Unexpected runtime schedule");
2307}
2308
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002309/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2310static OpenMPSchedType
2311getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2312 // only static is allowed for dist_schedule
2313 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2314}
2315
Alexander Musmanc6388682014-12-15 07:07:06 +00002316bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2317 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002318 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002319 return Schedule == OMP_sch_static;
2320}
2321
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002322bool CGOpenMPRuntime::isStaticNonchunked(
2323 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2324 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2325 return Schedule == OMP_dist_sch_static;
2326}
2327
2328
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002329bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002330 auto Schedule =
2331 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002332 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2333 return Schedule != OMP_sch_static;
2334}
2335
John McCall7f416cc2015-09-08 08:05:57 +00002336void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2337 SourceLocation Loc,
2338 OpenMPScheduleClauseKind ScheduleKind,
2339 unsigned IVSize, bool IVSigned,
2340 bool Ordered, llvm::Value *UB,
2341 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002342 if (!CGF.HaveInsertPoint())
2343 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002344 OpenMPSchedType Schedule =
2345 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002346 assert(Ordered ||
2347 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2348 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
2349 // Call __kmpc_dispatch_init(
2350 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2351 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2352 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002353
John McCall7f416cc2015-09-08 08:05:57 +00002354 // If the Chunk was not specified in the clause - use default value 1.
2355 if (Chunk == nullptr)
2356 Chunk = CGF.Builder.getIntN(IVSize, 1);
2357 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002358 emitUpdateLocation(CGF, Loc),
2359 getThreadID(CGF, Loc),
2360 CGF.Builder.getInt32(Schedule), // Schedule type
2361 CGF.Builder.getIntN(IVSize, 0), // Lower
2362 UB, // Upper
2363 CGF.Builder.getIntN(IVSize, 1), // Stride
2364 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002365 };
2366 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2367}
2368
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002369static void emitForStaticInitCall(CodeGenFunction &CGF,
2370 SourceLocation Loc,
2371 llvm::Value * UpdateLocation,
2372 llvm::Value * ThreadId,
2373 llvm::Constant * ForStaticInitFunction,
2374 OpenMPSchedType Schedule,
2375 unsigned IVSize, bool IVSigned, bool Ordered,
2376 Address IL, Address LB, Address UB,
2377 Address ST, llvm::Value *Chunk) {
2378 if (!CGF.HaveInsertPoint())
2379 return;
2380
2381 assert(!Ordered);
2382 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2383 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2384 Schedule == OMP_dist_sch_static ||
2385 Schedule == OMP_dist_sch_static_chunked);
2386
2387 // Call __kmpc_for_static_init(
2388 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2389 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2390 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2391 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2392 if (Chunk == nullptr) {
2393 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2394 Schedule == OMP_dist_sch_static) &&
2395 "expected static non-chunked schedule");
2396 // If the Chunk was not specified in the clause - use default value 1.
2397 Chunk = CGF.Builder.getIntN(IVSize, 1);
2398 } else {
2399 assert((Schedule == OMP_sch_static_chunked ||
2400 Schedule == OMP_ord_static_chunked ||
2401 Schedule == OMP_dist_sch_static_chunked) &&
2402 "expected static chunked schedule");
2403 }
2404 llvm::Value *Args[] = {
2405 UpdateLocation,
2406 ThreadId,
2407 CGF.Builder.getInt32(Schedule), // Schedule type
2408 IL.getPointer(), // &isLastIter
2409 LB.getPointer(), // &LB
2410 UB.getPointer(), // &UB
2411 ST.getPointer(), // &Stride
2412 CGF.Builder.getIntN(IVSize, 1), // Incr
2413 Chunk // Chunk
2414 };
2415 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2416}
2417
John McCall7f416cc2015-09-08 08:05:57 +00002418void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2419 SourceLocation Loc,
2420 OpenMPScheduleClauseKind ScheduleKind,
2421 unsigned IVSize, bool IVSigned,
2422 bool Ordered, Address IL, Address LB,
2423 Address UB, Address ST,
2424 llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002425 OpenMPSchedType ScheduleNum = getRuntimeSchedule(ScheduleKind, Chunk != nullptr,
2426 Ordered);
2427 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2428 auto *ThreadId = getThreadID(CGF, Loc);
2429 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2430 emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2431 ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
2432}
John McCall7f416cc2015-09-08 08:05:57 +00002433
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002434void CGOpenMPRuntime::emitDistributeStaticInit(CodeGenFunction &CGF,
2435 SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind,
2436 unsigned IVSize, bool IVSigned,
2437 bool Ordered, Address IL, Address LB,
2438 Address UB, Address ST,
2439 llvm::Value *Chunk) {
2440 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2441 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2442 auto *ThreadId = getThreadID(CGF, Loc);
2443 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2444 emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2445 ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002446}
2447
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002448void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2449 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002450 if (!CGF.HaveInsertPoint())
2451 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002452 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002453 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002454 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2455 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002456}
2457
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002458void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2459 SourceLocation Loc,
2460 unsigned IVSize,
2461 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002462 if (!CGF.HaveInsertPoint())
2463 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002464 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002465 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002466 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2467}
2468
Alexander Musman92bdaab2015-03-12 13:37:50 +00002469llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2470 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002471 bool IVSigned, Address IL,
2472 Address LB, Address UB,
2473 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002474 // Call __kmpc_dispatch_next(
2475 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2476 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2477 // kmp_int[32|64] *p_stride);
2478 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002479 emitUpdateLocation(CGF, Loc),
2480 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002481 IL.getPointer(), // &isLastIter
2482 LB.getPointer(), // &Lower
2483 UB.getPointer(), // &Upper
2484 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002485 };
2486 llvm::Value *Call =
2487 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2488 return CGF.EmitScalarConversion(
2489 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002490 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002491}
2492
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002493void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2494 llvm::Value *NumThreads,
2495 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002496 if (!CGF.HaveInsertPoint())
2497 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002498 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2499 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002500 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002501 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002502 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2503 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002504}
2505
Alexey Bataev7f210c62015-06-18 13:40:03 +00002506void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2507 OpenMPProcBindClauseKind ProcBind,
2508 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002509 if (!CGF.HaveInsertPoint())
2510 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002511 // Constants for proc bind value accepted by the runtime.
2512 enum ProcBindTy {
2513 ProcBindFalse = 0,
2514 ProcBindTrue,
2515 ProcBindMaster,
2516 ProcBindClose,
2517 ProcBindSpread,
2518 ProcBindIntel,
2519 ProcBindDefault
2520 } RuntimeProcBind;
2521 switch (ProcBind) {
2522 case OMPC_PROC_BIND_master:
2523 RuntimeProcBind = ProcBindMaster;
2524 break;
2525 case OMPC_PROC_BIND_close:
2526 RuntimeProcBind = ProcBindClose;
2527 break;
2528 case OMPC_PROC_BIND_spread:
2529 RuntimeProcBind = ProcBindSpread;
2530 break;
2531 case OMPC_PROC_BIND_unknown:
2532 llvm_unreachable("Unsupported proc_bind value.");
2533 }
2534 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2535 llvm::Value *Args[] = {
2536 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2537 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2538 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2539}
2540
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002541void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2542 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002543 if (!CGF.HaveInsertPoint())
2544 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002545 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002546 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2547 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002548}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002549
Alexey Bataev62b63b12015-03-10 07:28:44 +00002550namespace {
2551/// \brief Indexes of fields for type kmp_task_t.
2552enum KmpTaskTFields {
2553 /// \brief List of shared variables.
2554 KmpTaskTShareds,
2555 /// \brief Task routine.
2556 KmpTaskTRoutine,
2557 /// \brief Partition id for the untied tasks.
2558 KmpTaskTPartId,
2559 /// \brief Function with call of destructors for private variables.
2560 KmpTaskTDestructors,
Alexey Bataev7292c292016-04-25 12:22:29 +00002561 /// (Taskloops only) Lower bound.
2562 KmpTaskTLowerBound,
2563 /// (Taskloops only) Upper bound.
2564 KmpTaskTUpperBound,
2565 /// (Taskloops only) Stride.
2566 KmpTaskTStride,
2567 /// (Taskloops only) Is last iteration flag.
2568 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00002569};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002570} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002571
Samuel Antaoee8fb302016-01-06 13:42:12 +00002572bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2573 // FIXME: Add other entries type when they become supported.
2574 return OffloadEntriesTargetRegion.empty();
2575}
2576
2577/// \brief Initialize target region entry.
2578void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2579 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2580 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002581 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002582 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2583 "only required for the device "
2584 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002585 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002586 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2587 ++OffloadingEntriesNum;
2588}
2589
2590void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2591 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2592 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002593 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002594 // If we are emitting code for a target, the entry is already initialized,
2595 // only has to be registered.
2596 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002597 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002598 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002599 auto &Entry =
2600 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002601 assert(Entry.isValid() && "Entry not initialized!");
2602 Entry.setAddress(Addr);
2603 Entry.setID(ID);
2604 return;
2605 } else {
2606 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002607 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002608 }
2609}
2610
2611bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002612 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2613 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002614 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2615 if (PerDevice == OffloadEntriesTargetRegion.end())
2616 return false;
2617 auto PerFile = PerDevice->second.find(FileID);
2618 if (PerFile == PerDevice->second.end())
2619 return false;
2620 auto PerParentName = PerFile->second.find(ParentName);
2621 if (PerParentName == PerFile->second.end())
2622 return false;
2623 auto PerLine = PerParentName->second.find(LineNum);
2624 if (PerLine == PerParentName->second.end())
2625 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002626 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002627 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002628 return false;
2629 return true;
2630}
2631
2632void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2633 const OffloadTargetRegionEntryInfoActTy &Action) {
2634 // Scan all target region entries and perform the provided action.
2635 for (auto &D : OffloadEntriesTargetRegion)
2636 for (auto &F : D.second)
2637 for (auto &P : F.second)
2638 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002639 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002640}
2641
2642/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2643/// \a Codegen. This is used to emit the two functions that register and
2644/// unregister the descriptor of the current compilation unit.
2645static llvm::Function *
2646createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2647 const RegionCodeGenTy &Codegen) {
2648 auto &C = CGM.getContext();
2649 FunctionArgList Args;
2650 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2651 /*Id=*/nullptr, C.VoidPtrTy);
2652 Args.push_back(&DummyPtr);
2653
2654 CodeGenFunction CGF(CGM);
2655 GlobalDecl();
John McCallc56a8b32016-03-11 04:30:31 +00002656 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002657 auto FTy = CGM.getTypes().GetFunctionType(FI);
2658 auto *Fn =
2659 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2660 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2661 Codegen(CGF);
2662 CGF.FinishFunction();
2663 return Fn;
2664}
2665
2666llvm::Function *
2667CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2668
2669 // If we don't have entries or if we are emitting code for the device, we
2670 // don't need to do anything.
2671 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2672 return nullptr;
2673
2674 auto &M = CGM.getModule();
2675 auto &C = CGM.getContext();
2676
2677 // Get list of devices we care about
2678 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2679
2680 // We should be creating an offloading descriptor only if there are devices
2681 // specified.
2682 assert(!Devices.empty() && "No OpenMP offloading devices??");
2683
2684 // Create the external variables that will point to the begin and end of the
2685 // host entries section. These will be defined by the linker.
2686 auto *OffloadEntryTy =
2687 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2688 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2689 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002690 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002691 ".omp_offloading.entries_begin");
2692 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2693 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002694 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002695 ".omp_offloading.entries_end");
2696
2697 // Create all device images
2698 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2699 auto *DeviceImageTy = cast<llvm::StructType>(
2700 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2701
2702 for (unsigned i = 0; i < Devices.size(); ++i) {
2703 StringRef T = Devices[i].getTriple();
2704 auto *ImgBegin = new llvm::GlobalVariable(
2705 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002706 /*Initializer=*/nullptr,
2707 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002708 auto *ImgEnd = new llvm::GlobalVariable(
2709 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002710 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002711
2712 llvm::Constant *Dev =
2713 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2714 HostEntriesBegin, HostEntriesEnd, nullptr);
2715 DeviceImagesEntires.push_back(Dev);
2716 }
2717
2718 // Create device images global array.
2719 llvm::ArrayType *DeviceImagesInitTy =
2720 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2721 llvm::Constant *DeviceImagesInit =
2722 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2723
2724 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2725 M, DeviceImagesInitTy, /*isConstant=*/true,
2726 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2727 ".omp_offloading.device_images");
2728 DeviceImages->setUnnamedAddr(true);
2729
2730 // This is a Zero array to be used in the creation of the constant expressions
2731 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2732 llvm::Constant::getNullValue(CGM.Int32Ty)};
2733
2734 // Create the target region descriptor.
2735 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2736 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2737 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2738 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2739 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2740 Index),
2741 HostEntriesBegin, HostEntriesEnd, nullptr);
2742
2743 auto *Desc = new llvm::GlobalVariable(
2744 M, BinaryDescriptorTy, /*isConstant=*/true,
2745 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2746 ".omp_offloading.descriptor");
2747
2748 // Emit code to register or unregister the descriptor at execution
2749 // startup or closing, respectively.
2750
2751 // Create a variable to drive the registration and unregistration of the
2752 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2753 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2754 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2755 IdentInfo, C.CharTy);
2756
2757 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002758 CGM, ".omp_offloading.descriptor_unreg",
2759 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002760 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2761 Desc);
2762 });
2763 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002764 CGM, ".omp_offloading.descriptor_reg",
2765 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002766 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2767 Desc);
2768 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2769 });
2770 return RegFn;
2771}
2772
Samuel Antao2de62b02016-02-13 23:35:10 +00002773void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2774 llvm::Constant *Addr, uint64_t Size) {
2775 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002776 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2777 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2778 llvm::LLVMContext &C = CGM.getModule().getContext();
2779 llvm::Module &M = CGM.getModule();
2780
2781 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002782 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002783
2784 // Create constant string with the name.
2785 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2786
2787 llvm::GlobalVariable *Str =
2788 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2789 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2790 ".omp_offloading.entry_name");
2791 Str->setUnnamedAddr(true);
2792 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2793
2794 // Create the entry struct.
2795 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2796 TgtOffloadEntryType, AddrPtr, StrPtr,
2797 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2798 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2799 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2800 EntryInit, ".omp_offloading.entry");
2801
2802 // The entry has to be created in the section the linker expects it to be.
2803 Entry->setSection(".omp_offloading.entries");
2804 // We can't have any padding between symbols, so we need to have 1-byte
2805 // alignment.
2806 Entry->setAlignment(1);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002807}
2808
2809void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2810 // Emit the offloading entries and metadata so that the device codegen side
2811 // can
2812 // easily figure out what to emit. The produced metadata looks like this:
2813 //
2814 // !omp_offload.info = !{!1, ...}
2815 //
2816 // Right now we only generate metadata for function that contain target
2817 // regions.
2818
2819 // If we do not have entries, we dont need to do anything.
2820 if (OffloadEntriesInfoManager.empty())
2821 return;
2822
2823 llvm::Module &M = CGM.getModule();
2824 llvm::LLVMContext &C = M.getContext();
2825 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2826 OrderedEntries(OffloadEntriesInfoManager.size());
2827
2828 // Create the offloading info metadata node.
2829 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2830
2831 // Auxiliar methods to create metadata values and strings.
2832 auto getMDInt = [&](unsigned v) {
2833 return llvm::ConstantAsMetadata::get(
2834 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2835 };
2836
2837 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2838
2839 // Create function that emits metadata for each target region entry;
2840 auto &&TargetRegionMetadataEmitter = [&](
2841 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002842 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2843 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2844 // Generate metadata for target regions. Each entry of this metadata
2845 // contains:
2846 // - Entry 0 -> Kind of this type of metadata (0).
2847 // - Entry 1 -> Device ID of the file where the entry was identified.
2848 // - Entry 2 -> File ID of the file where the entry was identified.
2849 // - Entry 3 -> Mangled name of the function where the entry was identified.
2850 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002851 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002852 // The first element of the metadata node is the kind.
2853 Ops.push_back(getMDInt(E.getKind()));
2854 Ops.push_back(getMDInt(DeviceID));
2855 Ops.push_back(getMDInt(FileID));
2856 Ops.push_back(getMDString(ParentName));
2857 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002858 Ops.push_back(getMDInt(E.getOrder()));
2859
2860 // Save this entry in the right position of the ordered entries array.
2861 OrderedEntries[E.getOrder()] = &E;
2862
2863 // Add metadata to the named metadata node.
2864 MD->addOperand(llvm::MDNode::get(C, Ops));
2865 };
2866
2867 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2868 TargetRegionMetadataEmitter);
2869
2870 for (auto *E : OrderedEntries) {
2871 assert(E && "All ordered entries must exist!");
2872 if (auto *CE =
2873 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2874 E)) {
2875 assert(CE->getID() && CE->getAddress() &&
2876 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002877 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002878 } else
2879 llvm_unreachable("Unsupported entry kind.");
2880 }
2881}
2882
2883/// \brief Loads all the offload entries information from the host IR
2884/// metadata.
2885void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2886 // If we are in target mode, load the metadata from the host IR. This code has
2887 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2888
2889 if (!CGM.getLangOpts().OpenMPIsDevice)
2890 return;
2891
2892 if (CGM.getLangOpts().OMPHostIRFile.empty())
2893 return;
2894
2895 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2896 if (Buf.getError())
2897 return;
2898
2899 llvm::LLVMContext C;
2900 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2901
2902 if (ME.getError())
2903 return;
2904
2905 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2906 if (!MD)
2907 return;
2908
2909 for (auto I : MD->operands()) {
2910 llvm::MDNode *MN = cast<llvm::MDNode>(I);
2911
2912 auto getMDInt = [&](unsigned Idx) {
2913 llvm::ConstantAsMetadata *V =
2914 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2915 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2916 };
2917
2918 auto getMDString = [&](unsigned Idx) {
2919 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2920 return V->getString();
2921 };
2922
2923 switch (getMDInt(0)) {
2924 default:
2925 llvm_unreachable("Unexpected metadata!");
2926 break;
2927 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2928 OFFLOAD_ENTRY_INFO_TARGET_REGION:
2929 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2930 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2931 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00002932 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002933 break;
2934 }
2935 }
2936}
2937
Alexey Bataev62b63b12015-03-10 07:28:44 +00002938void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2939 if (!KmpRoutineEntryPtrTy) {
2940 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2941 auto &C = CGM.getContext();
2942 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2943 FunctionProtoType::ExtProtoInfo EPI;
2944 KmpRoutineEntryPtrQTy = C.getPointerType(
2945 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2946 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2947 }
2948}
2949
Alexey Bataevc71a4092015-09-11 10:29:41 +00002950static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2951 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002952 auto *Field = FieldDecl::Create(
2953 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2954 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2955 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2956 Field->setAccess(AS_public);
2957 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002958 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002959}
2960
Samuel Antaoee8fb302016-01-06 13:42:12 +00002961QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2962
2963 // Make sure the type of the entry is already created. This is the type we
2964 // have to create:
2965 // struct __tgt_offload_entry{
2966 // void *addr; // Pointer to the offload entry info.
2967 // // (function or global)
2968 // char *name; // Name of the function or global.
2969 // size_t size; // Size of the entry info (0 if it a function).
2970 // };
2971 if (TgtOffloadEntryQTy.isNull()) {
2972 ASTContext &C = CGM.getContext();
2973 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2974 RD->startDefinition();
2975 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2976 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2977 addFieldToRecordDecl(C, RD, C.getSizeType());
2978 RD->completeDefinition();
2979 TgtOffloadEntryQTy = C.getRecordType(RD);
2980 }
2981 return TgtOffloadEntryQTy;
2982}
2983
2984QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2985 // These are the types we need to build:
2986 // struct __tgt_device_image{
2987 // void *ImageStart; // Pointer to the target code start.
2988 // void *ImageEnd; // Pointer to the target code end.
2989 // // We also add the host entries to the device image, as it may be useful
2990 // // for the target runtime to have access to that information.
2991 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
2992 // // the entries.
2993 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2994 // // entries (non inclusive).
2995 // };
2996 if (TgtDeviceImageQTy.isNull()) {
2997 ASTContext &C = CGM.getContext();
2998 auto *RD = C.buildImplicitRecord("__tgt_device_image");
2999 RD->startDefinition();
3000 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3001 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3002 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3003 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3004 RD->completeDefinition();
3005 TgtDeviceImageQTy = C.getRecordType(RD);
3006 }
3007 return TgtDeviceImageQTy;
3008}
3009
3010QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3011 // struct __tgt_bin_desc{
3012 // int32_t NumDevices; // Number of devices supported.
3013 // __tgt_device_image *DeviceImages; // Arrays of device images
3014 // // (one per device).
3015 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3016 // // entries.
3017 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3018 // // entries (non inclusive).
3019 // };
3020 if (TgtBinaryDescriptorQTy.isNull()) {
3021 ASTContext &C = CGM.getContext();
3022 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3023 RD->startDefinition();
3024 addFieldToRecordDecl(
3025 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3026 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3027 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3028 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3029 RD->completeDefinition();
3030 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3031 }
3032 return TgtBinaryDescriptorQTy;
3033}
3034
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003035namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003036struct PrivateHelpersTy {
3037 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3038 const VarDecl *PrivateElemInit)
3039 : Original(Original), PrivateCopy(PrivateCopy),
3040 PrivateElemInit(PrivateElemInit) {}
3041 const VarDecl *Original;
3042 const VarDecl *PrivateCopy;
3043 const VarDecl *PrivateElemInit;
3044};
3045typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003046} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003047
Alexey Bataev9e034042015-05-05 04:05:12 +00003048static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003049createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003050 if (!Privates.empty()) {
3051 auto &C = CGM.getContext();
3052 // Build struct .kmp_privates_t. {
3053 // /* private vars */
3054 // };
3055 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3056 RD->startDefinition();
3057 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003058 auto *VD = Pair.second.Original;
3059 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003060 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003061 auto *FD = addFieldToRecordDecl(C, RD, Type);
3062 if (VD->hasAttrs()) {
3063 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3064 E(VD->getAttrs().end());
3065 I != E; ++I)
3066 FD->addAttr(*I);
3067 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003068 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003069 RD->completeDefinition();
3070 return RD;
3071 }
3072 return nullptr;
3073}
3074
Alexey Bataev9e034042015-05-05 04:05:12 +00003075static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003076createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3077 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003078 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003079 auto &C = CGM.getContext();
3080 // Build struct kmp_task_t {
3081 // void * shareds;
3082 // kmp_routine_entry_t routine;
3083 // kmp_int32 part_id;
3084 // kmp_routine_entry_t destructors;
Alexey Bataev7292c292016-04-25 12:22:29 +00003085 // For taskloops additional fields:
3086 // kmp_uint64 lb;
3087 // kmp_uint64 ub;
3088 // kmp_int64 st;
3089 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003090 // };
3091 auto *RD = C.buildImplicitRecord("kmp_task_t");
3092 RD->startDefinition();
3093 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3094 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3095 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3096 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003097 if (isOpenMPTaskLoopDirective(Kind)) {
3098 QualType KmpUInt64Ty =
3099 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3100 QualType KmpInt64Ty =
3101 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3102 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3103 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3104 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3105 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3106 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003107 RD->completeDefinition();
3108 return RD;
3109}
3110
3111static RecordDecl *
3112createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003113 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003114 auto &C = CGM.getContext();
3115 // Build struct kmp_task_t_with_privates {
3116 // kmp_task_t task_data;
3117 // .kmp_privates_t. privates;
3118 // };
3119 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3120 RD->startDefinition();
3121 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003122 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3123 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3124 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003125 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003126 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003127}
3128
3129/// \brief Emit a proxy function which accepts kmp_task_t as the second
3130/// argument.
3131/// \code
3132/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003133/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003134/// For taskloops:
3135/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003136/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003137/// return 0;
3138/// }
3139/// \endcode
3140static llvm::Value *
3141emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003142 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3143 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003144 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003145 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3146 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003147 auto &C = CGM.getContext();
3148 FunctionArgList Args;
3149 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3150 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003151 /*Id=*/nullptr,
3152 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003153 Args.push_back(&GtidArg);
3154 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003155 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003156 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003157 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3158 auto *TaskEntry =
3159 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3160 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003161 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003162 CodeGenFunction CGF(CGM);
3163 CGF.disableDebugInfo();
3164 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3165
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003166 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003167 // tt,
3168 // For taskloops:
3169 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3170 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003171 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003172 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003173 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3174 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3175 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003176 auto *KmpTaskTWithPrivatesQTyRD =
3177 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003178 LValue Base =
3179 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003180 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3181 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3182 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003183 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003184
3185 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3186 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003187 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003188 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003189 CGF.ConvertTypeForMem(SharedsPtrTy));
3190
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003191 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3192 llvm::Value *PrivatesParam;
3193 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3194 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3195 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003196 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003197 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003198 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003199
Alexey Bataev7292c292016-04-25 12:22:29 +00003200 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3201 TaskPrivatesMap,
3202 CGF.Builder
3203 .CreatePointerBitCastOrAddrSpaceCast(
3204 TDBase.getAddress(), CGF.VoidPtrTy)
3205 .getPointer()};
3206 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3207 std::end(CommonArgs));
3208 if (isOpenMPTaskLoopDirective(Kind)) {
3209 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3210 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3211 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3212 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3213 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3214 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3215 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3216 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3217 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3218 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3219 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3220 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3221 CallArgs.push_back(LBParam);
3222 CallArgs.push_back(UBParam);
3223 CallArgs.push_back(StParam);
3224 CallArgs.push_back(LIParam);
3225 }
3226 CallArgs.push_back(SharedsParam);
3227
Alexey Bataev62b63b12015-03-10 07:28:44 +00003228 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3229 CGF.EmitStoreThroughLValue(
3230 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003231 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003232 CGF.FinishFunction();
3233 return TaskEntry;
3234}
3235
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003236static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3237 SourceLocation Loc,
3238 QualType KmpInt32Ty,
3239 QualType KmpTaskTWithPrivatesPtrQTy,
3240 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003241 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003242 FunctionArgList Args;
3243 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3244 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003245 /*Id=*/nullptr,
3246 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003247 Args.push_back(&GtidArg);
3248 Args.push_back(&TaskTypeArg);
3249 FunctionType::ExtInfo Info;
3250 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003251 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003252 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3253 auto *DestructorFn =
3254 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3255 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003256 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3257 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003258 CodeGenFunction CGF(CGM);
3259 CGF.disableDebugInfo();
3260 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3261 Args);
3262
Alexey Bataev31300ed2016-02-04 11:27:03 +00003263 LValue Base = CGF.EmitLoadOfPointerLValue(
3264 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3265 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003266 auto *KmpTaskTWithPrivatesQTyRD =
3267 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3268 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003269 Base = CGF.EmitLValueForField(Base, *FI);
3270 for (auto *Field :
3271 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3272 if (auto DtorKind = Field->getType().isDestructedType()) {
3273 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3274 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3275 }
3276 }
3277 CGF.FinishFunction();
3278 return DestructorFn;
3279}
3280
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003281/// \brief Emit a privates mapping function for correct handling of private and
3282/// firstprivate variables.
3283/// \code
3284/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3285/// **noalias priv1,..., <tyn> **noalias privn) {
3286/// *priv1 = &.privates.priv1;
3287/// ...;
3288/// *privn = &.privates.privn;
3289/// }
3290/// \endcode
3291static llvm::Value *
3292emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003293 ArrayRef<const Expr *> PrivateVars,
3294 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003295 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003296 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003297 auto &C = CGM.getContext();
3298 FunctionArgList Args;
3299 ImplicitParamDecl TaskPrivatesArg(
3300 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3301 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3302 Args.push_back(&TaskPrivatesArg);
3303 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3304 unsigned Counter = 1;
3305 for (auto *E: PrivateVars) {
3306 Args.push_back(ImplicitParamDecl::Create(
3307 C, /*DC=*/nullptr, Loc,
3308 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3309 .withConst()
3310 .withRestrict()));
3311 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3312 PrivateVarsPos[VD] = Counter;
3313 ++Counter;
3314 }
3315 for (auto *E : FirstprivateVars) {
3316 Args.push_back(ImplicitParamDecl::Create(
3317 C, /*DC=*/nullptr, Loc,
3318 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3319 .withConst()
3320 .withRestrict()));
3321 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3322 PrivateVarsPos[VD] = Counter;
3323 ++Counter;
3324 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003325 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003326 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003327 auto *TaskPrivatesMapTy =
3328 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3329 auto *TaskPrivatesMap = llvm::Function::Create(
3330 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3331 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003332 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3333 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003334 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003335 CodeGenFunction CGF(CGM);
3336 CGF.disableDebugInfo();
3337 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3338 TaskPrivatesMapFnInfo, Args);
3339
3340 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003341 LValue Base = CGF.EmitLoadOfPointerLValue(
3342 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3343 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003344 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3345 Counter = 0;
3346 for (auto *Field : PrivatesQTyRD->fields()) {
3347 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3348 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003349 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003350 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3351 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003352 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003353 ++Counter;
3354 }
3355 CGF.FinishFunction();
3356 return TaskPrivatesMap;
3357}
3358
Alexey Bataev9e034042015-05-05 04:05:12 +00003359static int array_pod_sort_comparator(const PrivateDataTy *P1,
3360 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003361 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3362}
3363
Alexey Bataev7292c292016-04-25 12:22:29 +00003364CGOpenMPRuntime::TaskDataTy CGOpenMPRuntime::emitTaskInit(
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003365 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3366 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
Alexey Bataev48591dd2016-04-20 04:01:36 +00003367 unsigned NumberOfParts, llvm::Value *TaskFunction, QualType SharedsTy,
Alexey Bataev7292c292016-04-25 12:22:29 +00003368 Address Shareds, ArrayRef<const Expr *> PrivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003369 ArrayRef<const Expr *> PrivateCopies,
3370 ArrayRef<const Expr *> FirstprivateVars,
3371 ArrayRef<const Expr *> FirstprivateCopies,
Alexey Bataev7292c292016-04-25 12:22:29 +00003372 ArrayRef<const Expr *> FirstprivateInits) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003373 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00003374 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003375 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00003376 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003377 for (auto *E : PrivateVars) {
3378 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3379 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003380 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003381 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3382 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003383 ++I;
3384 }
Alexey Bataev9e034042015-05-05 04:05:12 +00003385 I = FirstprivateCopies.begin();
3386 auto IElemInitRef = FirstprivateInits.begin();
3387 for (auto *E : FirstprivateVars) {
3388 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3389 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003390 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003391 PrivateHelpersTy(
3392 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3393 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003394 ++I;
3395 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003396 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003397 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3398 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003399 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3400 // Build type kmp_routine_entry_t (if not built yet).
3401 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003402 // Build type kmp_task_t (if not built yet).
3403 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003404 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3405 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003406 }
3407 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003408 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003409 auto *KmpTaskTWithPrivatesQTyRD =
3410 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3411 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3412 QualType KmpTaskTWithPrivatesPtrQTy =
3413 C.getPointerType(KmpTaskTWithPrivatesQTy);
3414 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3415 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003416 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003417 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3418
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003419 // Emit initial values for private copies (if any).
3420 llvm::Value *TaskPrivatesMap = nullptr;
3421 auto *TaskPrivatesMapTy =
3422 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3423 3)
3424 ->getType();
3425 if (!Privates.empty()) {
3426 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3427 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3428 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
3429 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3430 TaskPrivatesMap, TaskPrivatesMapTy);
3431 } else {
3432 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3433 cast<llvm::PointerType>(TaskPrivatesMapTy));
3434 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003435 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3436 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003437 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003438 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3439 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3440 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003441
3442 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3443 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3444 // kmp_routine_entry_t *task_entry);
3445 // Task flags. Format is taken from
3446 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3447 // description of kmp_tasking_flags struct.
3448 const unsigned TiedFlag = 0x1;
3449 const unsigned FinalFlag = 0x2;
3450 unsigned Flags = Tied ? TiedFlag : 0;
3451 auto *TaskFlags =
3452 Final.getPointer()
3453 ? CGF.Builder.CreateSelect(Final.getPointer(),
3454 CGF.Builder.getInt32(FinalFlag),
3455 CGF.Builder.getInt32(/*C=*/0))
3456 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
3457 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003458 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003459 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3460 getThreadID(CGF, Loc), TaskFlags,
3461 KmpTaskTWithPrivatesTySize, SharedsSize,
3462 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3463 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003464 auto *NewTask = CGF.EmitRuntimeCall(
3465 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003466 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3467 NewTask, KmpTaskTWithPrivatesPtrTy);
3468 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3469 KmpTaskTWithPrivatesQTy);
3470 LValue TDBase =
3471 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003472 // Fill the data in the resulting kmp_task_t record.
3473 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003474 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003475 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003476 KmpTaskSharedsPtr =
3477 Address(CGF.EmitLoadOfScalar(
3478 CGF.EmitLValueForField(
3479 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3480 KmpTaskTShareds)),
3481 Loc),
3482 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003483 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003484 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003485 // Emit initial values for private copies (if any).
3486 bool NeedsCleanup = false;
3487 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003488 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3489 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003490 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003491 LValue SharedsBase;
3492 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00003493 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003494 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3495 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3496 SharedsTy);
3497 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003498 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3499 cast<CapturedStmt>(*D.getAssociatedStmt()));
3500 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003501 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003502 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003503 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003504 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003505 if (auto *Elem = Pair.second.PrivateElemInit) {
3506 auto *OriginalVD = Pair.second.Original;
3507 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3508 auto SharedRefLValue =
3509 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003510 SharedRefLValue = CGF.MakeAddrLValue(
3511 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3512 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003513 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003514 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003515 // Initialize firstprivate array.
3516 if (!isa<CXXConstructExpr>(Init) ||
3517 CGF.isTrivialInitializer(Init)) {
3518 // Perform simple memcpy.
3519 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003520 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00003521 } else {
3522 // Initialize firstprivate array using element-by-element
3523 // intialization.
3524 CGF.EmitOMPAggregateAssign(
3525 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003526 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00003527 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003528 // Clean up any temporaries needed by the initialization.
3529 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003530 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003531 return SrcElement;
3532 });
3533 (void)InitScope.Privatize();
3534 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00003535 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3536 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003537 CGF.EmitAnyExprToMem(Init, DestElement,
3538 Init->getType().getQualifiers(),
3539 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003540 });
3541 }
3542 } else {
3543 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003544 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003545 return SharedRefLValue.getAddress();
3546 });
3547 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00003548 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003549 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3550 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003551 }
3552 } else {
3553 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3554 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003555 }
3556 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003557 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003558 }
3559 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003560 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003561 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003562 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
3563 KmpTaskTWithPrivatesPtrQTy,
3564 KmpTaskTWithPrivatesQTy)
3565 : llvm::ConstantPointerNull::get(
3566 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
3567 LValue Destructor = CGF.EmitLValueForField(
3568 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
3569 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3570 DestructorFn, KmpRoutineEntryPtrTy),
3571 Destructor);
Alexey Bataev7292c292016-04-25 12:22:29 +00003572 TaskDataTy Data;
3573 Data.NewTask = NewTask;
3574 Data.TaskEntry = TaskEntry;
3575 Data.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3576 Data.TDBase = TDBase;
3577 Data.KmpTaskTQTyRD = KmpTaskTQTyRD;
3578 return Data;
3579}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003580
Alexey Bataev7292c292016-04-25 12:22:29 +00003581void CGOpenMPRuntime::emitTaskCall(
3582 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3583 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
3584 unsigned NumberOfParts, llvm::Value *TaskFunction, QualType SharedsTy,
3585 Address Shareds, const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3586 ArrayRef<const Expr *> PrivateCopies,
3587 ArrayRef<const Expr *> FirstprivateVars,
3588 ArrayRef<const Expr *> FirstprivateCopies,
3589 ArrayRef<const Expr *> FirstprivateInits,
3590 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
3591 if (!CGF.HaveInsertPoint())
3592 return;
3593
3594 TaskDataTy Data =
3595 emitTaskInit(CGF, Loc, D, Tied, Final, NumberOfParts, TaskFunction,
3596 SharedsTy, Shareds, PrivateVars, PrivateCopies,
3597 FirstprivateVars, FirstprivateCopies, FirstprivateInits);
3598 llvm::Value *NewTask = Data.NewTask;
3599 llvm::Value *TaskEntry = Data.TaskEntry;
3600 llvm::Value *NewTaskNewTaskTTy = Data.NewTaskNewTaskTTy;
3601 LValue TDBase = Data.TDBase;
3602 RecordDecl *KmpTaskTQTyRD = Data.KmpTaskTQTyRD;
3603 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003604 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003605 Address DependenciesArray = Address::invalid();
3606 unsigned NumDependencies = Dependences.size();
3607 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003608 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003609 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003610 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3611 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003612 QualType FlagsTy =
3613 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003614 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3615 if (KmpDependInfoTy.isNull()) {
3616 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3617 KmpDependInfoRD->startDefinition();
3618 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3619 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3620 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3621 KmpDependInfoRD->completeDefinition();
3622 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3623 } else {
3624 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3625 }
John McCall7f416cc2015-09-08 08:05:57 +00003626 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003627 // Define type kmp_depend_info[<Dependences.size()>];
3628 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003629 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003630 ArrayType::Normal, /*IndexTypeQuals=*/0);
3631 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00003632 DependenciesArray =
3633 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00003634 for (unsigned i = 0; i < NumDependencies; ++i) {
3635 const Expr *E = Dependences[i].second;
3636 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003637 llvm::Value *Size;
3638 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003639 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3640 LValue UpAddrLVal =
3641 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3642 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003643 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003644 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003645 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003646 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3647 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003648 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003649 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003650 auto Base = CGF.MakeAddrLValue(
3651 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003652 KmpDependInfoTy);
3653 // deps[i].base_addr = &<Dependences[i].second>;
3654 auto BaseAddrLVal = CGF.EmitLValueForField(
3655 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003656 CGF.EmitStoreOfScalar(
3657 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3658 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003659 // deps[i].len = sizeof(<Dependences[i].second>);
3660 auto LenLVal = CGF.EmitLValueForField(
3661 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3662 CGF.EmitStoreOfScalar(Size, LenLVal);
3663 // deps[i].flags = <Dependences[i].first>;
3664 RTLDependenceKindTy DepKind;
3665 switch (Dependences[i].first) {
3666 case OMPC_DEPEND_in:
3667 DepKind = DepIn;
3668 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003669 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003670 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003671 case OMPC_DEPEND_inout:
3672 DepKind = DepInOut;
3673 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003674 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003675 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003676 case OMPC_DEPEND_unknown:
3677 llvm_unreachable("Unknown task dependence type");
3678 }
3679 auto FlagsLVal = CGF.EmitLValueForField(
3680 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3681 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3682 FlagsLVal);
3683 }
John McCall7f416cc2015-09-08 08:05:57 +00003684 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3685 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003686 CGF.VoidPtrTy);
3687 }
3688
Alexey Bataev62b63b12015-03-10 07:28:44 +00003689 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3690 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003691 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3692 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3693 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3694 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003695 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003696 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003697 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3698 llvm::Value *DepTaskArgs[7];
3699 if (NumDependencies) {
3700 DepTaskArgs[0] = UpLoc;
3701 DepTaskArgs[1] = ThreadID;
3702 DepTaskArgs[2] = NewTask;
3703 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3704 DepTaskArgs[4] = DependenciesArray.getPointer();
3705 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3706 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3707 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00003708 auto &&ThenCodeGen = [this, Tied, Loc, NumberOfParts, TDBase, KmpTaskTQTyRD,
3709 NumDependencies, &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003710 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003711 if (!Tied) {
3712 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3713 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
3714 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
3715 }
John McCall7f416cc2015-09-08 08:05:57 +00003716 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003717 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00003718 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00003719 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003720 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00003721 TaskArgs);
3722 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00003723 // Check if parent region is untied and build return for untied task;
3724 if (auto *Region =
3725 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3726 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00003727 };
John McCall7f416cc2015-09-08 08:05:57 +00003728
3729 llvm::Value *DepWaitTaskArgs[6];
3730 if (NumDependencies) {
3731 DepWaitTaskArgs[0] = UpLoc;
3732 DepWaitTaskArgs[1] = ThreadID;
3733 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3734 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3735 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3736 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3737 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003738 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
3739 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
3740 PrePostActionTy &) {
3741 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003742 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3743 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3744 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3745 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3746 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00003747 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003748 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003749 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003750 // Call proxy_task_entry(gtid, new_task);
3751 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
3752 CodeGenFunction &CGF, PrePostActionTy &Action) {
3753 Action.Enter(CGF);
3754 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3755 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3756 };
3757
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003758 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3759 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003760 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3761 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003762 RegionCodeGenTy RCG(CodeGen);
3763 CommonActionTy Action(
3764 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
3765 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
3766 RCG.setAction(Action);
3767 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003768 };
John McCall7f416cc2015-09-08 08:05:57 +00003769
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003770 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00003771 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003772 else {
3773 RegionCodeGenTy ThenRCG(ThenCodeGen);
3774 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00003775 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003776}
3777
Alexey Bataev7292c292016-04-25 12:22:29 +00003778void CGOpenMPRuntime::emitTaskLoopCall(
3779 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
3780 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final, bool Nogroup,
3781 unsigned NumberOfParts, llvm::Value *TaskFunction, QualType SharedsTy,
3782 Address Shareds, const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3783 ArrayRef<const Expr *> PrivateCopies,
3784 ArrayRef<const Expr *> FirstprivateVars,
3785 ArrayRef<const Expr *> FirstprivateCopies,
3786 ArrayRef<const Expr *> FirstprivateInits) {
3787 if (!CGF.HaveInsertPoint())
3788 return;
3789 TaskDataTy Data =
3790 emitTaskInit(CGF, Loc, D, Tied, Final, NumberOfParts, TaskFunction,
3791 SharedsTy, Shareds, PrivateVars, PrivateCopies,
3792 FirstprivateVars, FirstprivateCopies, FirstprivateInits);
3793 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3794 // libcall.
3795 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
3796 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
3797 // sched, kmp_uint64 grainsize, void *task_dup);
3798 llvm::Value *ThreadID = getThreadID(CGF, Loc);
3799 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
3800 llvm::Value *IfVal;
3801 if (IfCond) {
3802 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
3803 /*isSigned=*/true);
3804 } else
3805 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
3806
3807 LValue LBLVal = CGF.EmitLValueForField(
3808 Data.TDBase,
3809 *std::next(Data.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
3810 auto *LBVar =
3811 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
3812 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
3813 /*IsInitializer=*/true);
3814 LValue UBLVal = CGF.EmitLValueForField(
3815 Data.TDBase,
3816 *std::next(Data.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
3817 auto *UBVar =
3818 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
3819 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
3820 /*IsInitializer=*/true);
3821 LValue StLVal = CGF.EmitLValueForField(
3822 Data.TDBase,
3823 *std::next(Data.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
3824 auto *StVar =
3825 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
3826 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
3827 /*IsInitializer=*/true);
3828 llvm::Value *TaskArgs[] = {
3829 UpLoc,
3830 ThreadID,
3831 Data.NewTask,
3832 IfVal,
3833 LBLVal.getPointer(),
3834 UBLVal.getPointer(),
3835 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
3836 llvm::ConstantInt::getSigned(CGF.IntTy, Nogroup ? 1 : 0),
3837 llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/0),
3838 llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
3839 llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
3840 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
3841}
3842
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003843/// \brief Emit reduction operation for each element of array (required for
3844/// array sections) LHS op = RHS.
3845/// \param Type Type of array.
3846/// \param LHSVar Variable on the left side of the reduction operation
3847/// (references element of array in original variable).
3848/// \param RHSVar Variable on the right side of the reduction operation
3849/// (references element of array in original variable).
3850/// \param RedOpGen Generator of reduction operation with use of LHSVar and
3851/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00003852static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003853 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3854 const VarDecl *RHSVar,
3855 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3856 const Expr *, const Expr *)> &RedOpGen,
3857 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3858 const Expr *UpExpr = nullptr) {
3859 // Perform element-by-element initialization.
3860 QualType ElementTy;
3861 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3862 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3863
3864 // Drill down to the base element type on both arrays.
3865 auto ArrayTy = Type->getAsArrayTypeUnsafe();
3866 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3867
3868 auto RHSBegin = RHSAddr.getPointer();
3869 auto LHSBegin = LHSAddr.getPointer();
3870 // Cast from pointer to array type to pointer to single element.
3871 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3872 // The basic structure here is a while-do loop.
3873 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3874 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3875 auto IsEmpty =
3876 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3877 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3878
3879 // Enter the loop body, making that address the current address.
3880 auto EntryBB = CGF.Builder.GetInsertBlock();
3881 CGF.EmitBlock(BodyBB);
3882
3883 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3884
3885 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3886 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3887 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3888 Address RHSElementCurrent =
3889 Address(RHSElementPHI,
3890 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3891
3892 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3893 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3894 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3895 Address LHSElementCurrent =
3896 Address(LHSElementPHI,
3897 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3898
3899 // Emit copy.
3900 CodeGenFunction::OMPPrivateScope Scope(CGF);
3901 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3902 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3903 Scope.Privatize();
3904 RedOpGen(CGF, XExpr, EExpr, UpExpr);
3905 Scope.ForceCleanup();
3906
3907 // Shift the address forward by one element.
3908 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3909 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3910 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3911 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3912 // Check whether we've reached the end.
3913 auto Done =
3914 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3915 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3916 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3917 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3918
3919 // Done.
3920 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3921}
3922
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003923/// Emit reduction combiner. If the combiner is a simple expression emit it as
3924/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
3925/// UDR combiner function.
3926static void emitReductionCombiner(CodeGenFunction &CGF,
3927 const Expr *ReductionOp) {
3928 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
3929 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
3930 if (auto *DRE =
3931 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
3932 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
3933 std::pair<llvm::Function *, llvm::Function *> Reduction =
3934 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
3935 RValue Func = RValue::get(Reduction.first);
3936 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
3937 CGF.EmitIgnoredExpr(ReductionOp);
3938 return;
3939 }
3940 CGF.EmitIgnoredExpr(ReductionOp);
3941}
3942
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003943static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3944 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003945 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003946 ArrayRef<const Expr *> LHSExprs,
3947 ArrayRef<const Expr *> RHSExprs,
3948 ArrayRef<const Expr *> ReductionOps) {
3949 auto &C = CGM.getContext();
3950
3951 // void reduction_func(void *LHSArg, void *RHSArg);
3952 FunctionArgList Args;
3953 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3954 C.VoidPtrTy);
3955 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3956 C.VoidPtrTy);
3957 Args.push_back(&LHSArg);
3958 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00003959 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003960 auto *Fn = llvm::Function::Create(
3961 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3962 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003963 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003964 CodeGenFunction CGF(CGM);
3965 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3966
3967 // Dst = (void*[n])(LHSArg);
3968 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003969 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3970 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3971 ArgsType), CGF.getPointerAlign());
3972 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3973 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3974 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003975
3976 // ...
3977 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3978 // ...
3979 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003980 auto IPriv = Privates.begin();
3981 unsigned Idx = 0;
3982 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003983 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3984 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003985 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003986 });
3987 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3988 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003989 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003990 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003991 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003992 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003993 // Get array size and emit VLA type.
3994 ++Idx;
3995 Address Elem =
3996 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3997 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003998 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3999 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004000 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004001 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004002 CGF.EmitVariablyModifiedType(PrivTy);
4003 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004004 }
4005 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004006 IPriv = Privates.begin();
4007 auto ILHS = LHSExprs.begin();
4008 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004009 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004010 if ((*IPriv)->getType()->isArrayType()) {
4011 // Emit reduction for array section.
4012 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4013 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004014 EmitOMPAggregateReduction(
4015 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4016 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4017 emitReductionCombiner(CGF, E);
4018 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004019 } else
4020 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004021 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004022 ++IPriv;
4023 ++ILHS;
4024 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004025 }
4026 Scope.ForceCleanup();
4027 CGF.FinishFunction();
4028 return Fn;
4029}
4030
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004031static void emitSingleReductionCombiner(CodeGenFunction &CGF,
4032 const Expr *ReductionOp,
4033 const Expr *PrivateRef,
4034 const DeclRefExpr *LHS,
4035 const DeclRefExpr *RHS) {
4036 if (PrivateRef->getType()->isArrayType()) {
4037 // Emit reduction for array section.
4038 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4039 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4040 EmitOMPAggregateReduction(
4041 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4042 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4043 emitReductionCombiner(CGF, ReductionOp);
4044 });
4045 } else
4046 // Emit reduction for array subscript or single variable.
4047 emitReductionCombiner(CGF, ReductionOp);
4048}
4049
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004050void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004051 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004052 ArrayRef<const Expr *> LHSExprs,
4053 ArrayRef<const Expr *> RHSExprs,
4054 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004055 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004056 if (!CGF.HaveInsertPoint())
4057 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004058 // Next code should be emitted for reduction:
4059 //
4060 // static kmp_critical_name lock = { 0 };
4061 //
4062 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4063 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4064 // ...
4065 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4066 // *(Type<n>-1*)rhs[<n>-1]);
4067 // }
4068 //
4069 // ...
4070 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4071 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4072 // RedList, reduce_func, &<lock>)) {
4073 // case 1:
4074 // ...
4075 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4076 // ...
4077 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4078 // break;
4079 // case 2:
4080 // ...
4081 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4082 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004083 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004084 // break;
4085 // default:;
4086 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004087 //
4088 // if SimpleReduction is true, only the next code is generated:
4089 // ...
4090 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4091 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004092
4093 auto &C = CGM.getContext();
4094
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004095 if (SimpleReduction) {
4096 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004097 auto IPriv = Privates.begin();
4098 auto ILHS = LHSExprs.begin();
4099 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004100 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004101 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4102 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004103 ++IPriv;
4104 ++ILHS;
4105 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004106 }
4107 return;
4108 }
4109
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004110 // 1. Build a list of reduction variables.
4111 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004112 auto Size = RHSExprs.size();
4113 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004114 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004115 // Reserve place for array size.
4116 ++Size;
4117 }
4118 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004119 QualType ReductionArrayTy =
4120 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4121 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004122 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004123 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004124 auto IPriv = Privates.begin();
4125 unsigned Idx = 0;
4126 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004127 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004128 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004129 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004130 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004131 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4132 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004133 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004134 // Store array size.
4135 ++Idx;
4136 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4137 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004138 llvm::Value *Size = CGF.Builder.CreateIntCast(
4139 CGF.getVLASize(
4140 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4141 .first,
4142 CGF.SizeTy, /*isSigned=*/false);
4143 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4144 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004145 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004146 }
4147
4148 // 2. Emit reduce_func().
4149 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004150 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4151 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004152
4153 // 3. Create static kmp_critical_name lock = { 0 };
4154 auto *Lock = getCriticalRegionLock(".reduction");
4155
4156 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4157 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004158 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004159 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004160 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00004161 auto *RL =
4162 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
4163 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004164 llvm::Value *Args[] = {
4165 IdentTLoc, // ident_t *<loc>
4166 ThreadId, // i32 <gtid>
4167 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4168 ReductionArrayTySize, // size_type sizeof(RedList)
4169 RL, // void *RedList
4170 ReductionFn, // void (*) (void *, void *) <reduce_func>
4171 Lock // kmp_critical_name *&<lock>
4172 };
4173 auto Res = CGF.EmitRuntimeCall(
4174 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4175 : OMPRTL__kmpc_reduce),
4176 Args);
4177
4178 // 5. Build switch(res)
4179 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4180 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4181
4182 // 6. Build case 1:
4183 // ...
4184 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4185 // ...
4186 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4187 // break;
4188 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4189 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4190 CGF.EmitBlock(Case1BB);
4191
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004192 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4193 llvm::Value *EndArgs[] = {
4194 IdentTLoc, // ident_t *<loc>
4195 ThreadId, // i32 <gtid>
4196 Lock // kmp_critical_name *&<lock>
4197 };
4198 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4199 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004200 auto IPriv = Privates.begin();
4201 auto ILHS = LHSExprs.begin();
4202 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004203 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004204 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4205 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004206 ++IPriv;
4207 ++ILHS;
4208 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004209 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004210 };
4211 RegionCodeGenTy RCG(CodeGen);
4212 CommonActionTy Action(
4213 nullptr, llvm::None,
4214 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4215 : OMPRTL__kmpc_end_reduce),
4216 EndArgs);
4217 RCG.setAction(Action);
4218 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004219
4220 CGF.EmitBranch(DefaultBB);
4221
4222 // 7. Build case 2:
4223 // ...
4224 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4225 // ...
4226 // break;
4227 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4228 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4229 CGF.EmitBlock(Case2BB);
4230
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004231 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4232 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004233 auto ILHS = LHSExprs.begin();
4234 auto IRHS = RHSExprs.begin();
4235 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004236 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004237 const Expr *XExpr = nullptr;
4238 const Expr *EExpr = nullptr;
4239 const Expr *UpExpr = nullptr;
4240 BinaryOperatorKind BO = BO_Comma;
4241 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4242 if (BO->getOpcode() == BO_Assign) {
4243 XExpr = BO->getLHS();
4244 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004245 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004246 }
4247 // Try to emit update expression as a simple atomic.
4248 auto *RHSExpr = UpExpr;
4249 if (RHSExpr) {
4250 // Analyze RHS part of the whole expression.
4251 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4252 RHSExpr->IgnoreParenImpCasts())) {
4253 // If this is a conditional operator, analyze its condition for
4254 // min/max reduction operator.
4255 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004256 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004257 if (auto *BORHS =
4258 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4259 EExpr = BORHS->getRHS();
4260 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004261 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004262 }
4263 if (XExpr) {
4264 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4265 auto &&AtomicRedGen = [BO, VD, IPriv,
4266 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4267 const Expr *EExpr, const Expr *UpExpr) {
4268 LValue X = CGF.EmitLValue(XExpr);
4269 RValue E;
4270 if (EExpr)
4271 E = CGF.EmitAnyExpr(EExpr);
4272 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00004273 X, E, BO, /*IsXLHSInRHSPart=*/true,
4274 llvm::AtomicOrdering::Monotonic, Loc,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004275 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
4276 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4277 PrivateScope.addPrivate(
4278 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4279 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4280 CGF.emitOMPSimpleStore(
4281 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4282 VD->getType().getNonReferenceType(), Loc);
4283 return LHSTemp;
4284 });
4285 (void)PrivateScope.Privatize();
4286 return CGF.EmitAnyExpr(UpExpr);
4287 });
4288 };
4289 if ((*IPriv)->getType()->isArrayType()) {
4290 // Emit atomic reduction for array section.
4291 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4292 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4293 AtomicRedGen, XExpr, EExpr, UpExpr);
4294 } else
4295 // Emit atomic reduction for array subscript or single variable.
4296 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4297 } else {
4298 // Emit as a critical region.
4299 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4300 const Expr *, const Expr *) {
4301 auto &RT = CGF.CGM.getOpenMPRuntime();
4302 RT.emitCriticalRegion(
4303 CGF, ".atomic_reduction",
4304 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4305 Action.Enter(CGF);
4306 emitReductionCombiner(CGF, E);
4307 },
4308 Loc);
4309 };
4310 if ((*IPriv)->getType()->isArrayType()) {
4311 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4312 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4313 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4314 CritRedGen);
4315 } else
4316 CritRedGen(CGF, nullptr, nullptr, nullptr);
4317 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004318 ++ILHS;
4319 ++IRHS;
4320 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004321 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004322 };
4323 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4324 if (!WithNowait) {
4325 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4326 llvm::Value *EndArgs[] = {
4327 IdentTLoc, // ident_t *<loc>
4328 ThreadId, // i32 <gtid>
4329 Lock // kmp_critical_name *&<lock>
4330 };
4331 CommonActionTy Action(nullptr, llvm::None,
4332 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4333 EndArgs);
4334 AtomicRCG.setAction(Action);
4335 AtomicRCG(CGF);
4336 } else
4337 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004338
4339 CGF.EmitBranch(DefaultBB);
4340 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4341}
4342
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004343void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4344 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004345 if (!CGF.HaveInsertPoint())
4346 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004347 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4348 // global_tid);
4349 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4350 // Ignore return result until untied tasks are supported.
4351 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004352 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4353 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004354}
4355
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004356void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004357 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004358 const RegionCodeGenTy &CodeGen,
4359 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004360 if (!CGF.HaveInsertPoint())
4361 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004362 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004363 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004364}
4365
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004366namespace {
4367enum RTCancelKind {
4368 CancelNoreq = 0,
4369 CancelParallel = 1,
4370 CancelLoop = 2,
4371 CancelSections = 3,
4372 CancelTaskgroup = 4
4373};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004374} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004375
4376static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4377 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004378 if (CancelRegion == OMPD_parallel)
4379 CancelKind = CancelParallel;
4380 else if (CancelRegion == OMPD_for)
4381 CancelKind = CancelLoop;
4382 else if (CancelRegion == OMPD_sections)
4383 CancelKind = CancelSections;
4384 else {
4385 assert(CancelRegion == OMPD_taskgroup);
4386 CancelKind = CancelTaskgroup;
4387 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004388 return CancelKind;
4389}
4390
4391void CGOpenMPRuntime::emitCancellationPointCall(
4392 CodeGenFunction &CGF, SourceLocation Loc,
4393 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004394 if (!CGF.HaveInsertPoint())
4395 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004396 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4397 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004398 if (auto *OMPRegionInfo =
4399 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004400 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004401 llvm::Value *Args[] = {
4402 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4403 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004404 // Ignore return result until untied tasks are supported.
4405 auto *Result = CGF.EmitRuntimeCall(
4406 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4407 // if (__kmpc_cancellationpoint()) {
4408 // __kmpc_cancel_barrier();
4409 // exit from construct;
4410 // }
4411 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4412 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4413 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4414 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4415 CGF.EmitBlock(ExitBB);
4416 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004417 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004418 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004419 auto CancelDest =
4420 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004421 CGF.EmitBranchThroughCleanup(CancelDest);
4422 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4423 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004424 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004425}
4426
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004427void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004428 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004429 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004430 if (!CGF.HaveInsertPoint())
4431 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004432 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4433 // kmp_int32 cncl_kind);
4434 if (auto *OMPRegionInfo =
4435 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004436 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4437 PrePostActionTy &) {
4438 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004439 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004440 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004441 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4442 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004443 auto *Result = CGF.EmitRuntimeCall(
4444 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004445 // if (__kmpc_cancel()) {
4446 // __kmpc_cancel_barrier();
4447 // exit from construct;
4448 // }
4449 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4450 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4451 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4452 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4453 CGF.EmitBlock(ExitBB);
4454 // __kmpc_cancel_barrier();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004455 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev87933c72015-09-18 08:07:34 +00004456 // exit from construct;
4457 auto CancelDest =
4458 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4459 CGF.EmitBranchThroughCleanup(CancelDest);
4460 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4461 };
4462 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004463 emitOMPIfClause(CGF, IfCond, ThenGen,
4464 [](CodeGenFunction &, PrePostActionTy &) {});
4465 else {
4466 RegionCodeGenTy ThenRCG(ThenGen);
4467 ThenRCG(CGF);
4468 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004469 }
4470}
Samuel Antaobed3c462015-10-02 16:14:20 +00004471
Samuel Antaoee8fb302016-01-06 13:42:12 +00004472/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004473/// consists of the file and device IDs as well as line number associated with
4474/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004475static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4476 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004477 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004478
4479 auto &SM = C.getSourceManager();
4480
4481 // The loc should be always valid and have a file ID (the user cannot use
4482 // #pragma directives in macros)
4483
4484 assert(Loc.isValid() && "Source location is expected to be always valid.");
4485 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4486
4487 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4488 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4489
4490 llvm::sys::fs::UniqueID ID;
4491 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4492 llvm_unreachable("Source file with target region no longer exists!");
4493
4494 DeviceID = ID.getDevice();
4495 FileID = ID.getFile();
4496 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004497}
4498
4499void CGOpenMPRuntime::emitTargetOutlinedFunction(
4500 const OMPExecutableDirective &D, StringRef ParentName,
4501 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004502 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004503 assert(!ParentName.empty() && "Invalid target region parent name!");
4504
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004505 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4506 IsOffloadEntry, CodeGen);
4507}
4508
4509void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4510 const OMPExecutableDirective &D, StringRef ParentName,
4511 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4512 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004513 // Create a unique name for the entry function using the source location
4514 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004515 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004516 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004517 //
4518 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004519 // mangled name of the function that encloses the target region and BB is the
4520 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004521
4522 unsigned DeviceID;
4523 unsigned FileID;
4524 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004525 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004526 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004527 SmallString<64> EntryFnName;
4528 {
4529 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004530 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4531 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004532 }
4533
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004534 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4535
Samuel Antaobed3c462015-10-02 16:14:20 +00004536 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004537 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004538 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004539
4540 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4541
4542 // If this target outline function is not an offload entry, we don't need to
4543 // register it.
4544 if (!IsOffloadEntry)
4545 return;
4546
4547 // The target region ID is used by the runtime library to identify the current
4548 // target region, so it only has to be unique and not necessarily point to
4549 // anything. It could be the pointer to the outlined function that implements
4550 // the target region, but we aren't using that so that the compiler doesn't
4551 // need to keep that, and could therefore inline the host function if proven
4552 // worthwhile during optimization. In the other hand, if emitting code for the
4553 // device, the ID has to be the function address so that it can retrieved from
4554 // the offloading entry and launched by the runtime library. We also mark the
4555 // outlined function to have external linkage in case we are emitting code for
4556 // the device, because these functions will be entry points to the device.
4557
4558 if (CGM.getLangOpts().OpenMPIsDevice) {
4559 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4560 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4561 } else
4562 OutlinedFnID = new llvm::GlobalVariable(
4563 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4564 llvm::GlobalValue::PrivateLinkage,
4565 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4566
4567 // Register the information for the entry associated with this target region.
4568 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004569 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004570}
4571
Samuel Antaob68e2db2016-03-03 16:20:23 +00004572/// \brief Emit the num_teams clause of an enclosed teams directive at the
4573/// target region scope. If there is no teams directive associated with the
4574/// target directive, or if there is no num_teams clause associated with the
4575/// enclosed teams directive, return nullptr.
4576static llvm::Value *
4577emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4578 CodeGenFunction &CGF,
4579 const OMPExecutableDirective &D) {
4580
4581 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4582 "teams directive expected to be "
4583 "emitted only for the host!");
4584
4585 // FIXME: For the moment we do not support combined directives with target and
4586 // teams, so we do not expect to get any num_teams clause in the provided
4587 // directive. Once we support that, this assertion can be replaced by the
4588 // actual emission of the clause expression.
4589 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4590 "Not expecting clause in directive.");
4591
4592 // If the current target region has a teams region enclosed, we need to get
4593 // the number of teams to pass to the runtime function call. This is done
4594 // by generating the expression in a inlined region. This is required because
4595 // the expression is captured in the enclosing target environment when the
4596 // teams directive is not combined with target.
4597
4598 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4599
4600 // FIXME: Accommodate other combined directives with teams when they become
4601 // available.
4602 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4603 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4604 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4605 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4606 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4607 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4608 /*IsSigned=*/true);
4609 }
4610
4611 // If we have an enclosed teams directive but no num_teams clause we use
4612 // the default value 0.
4613 return CGF.Builder.getInt32(0);
4614 }
4615
4616 // No teams associated with the directive.
4617 return nullptr;
4618}
4619
4620/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4621/// target region scope. If there is no teams directive associated with the
4622/// target directive, or if there is no thread_limit clause associated with the
4623/// enclosed teams directive, return nullptr.
4624static llvm::Value *
4625emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4626 CodeGenFunction &CGF,
4627 const OMPExecutableDirective &D) {
4628
4629 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4630 "teams directive expected to be "
4631 "emitted only for the host!");
4632
4633 // FIXME: For the moment we do not support combined directives with target and
4634 // teams, so we do not expect to get any thread_limit clause in the provided
4635 // directive. Once we support that, this assertion can be replaced by the
4636 // actual emission of the clause expression.
4637 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4638 "Not expecting clause in directive.");
4639
4640 // If the current target region has a teams region enclosed, we need to get
4641 // the thread limit to pass to the runtime function call. This is done
4642 // by generating the expression in a inlined region. This is required because
4643 // the expression is captured in the enclosing target environment when the
4644 // teams directive is not combined with target.
4645
4646 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4647
4648 // FIXME: Accommodate other combined directives with teams when they become
4649 // available.
4650 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4651 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4652 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4653 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4654 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4655 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4656 /*IsSigned=*/true);
4657 }
4658
4659 // If we have an enclosed teams directive but no thread_limit clause we use
4660 // the default value 0.
4661 return CGF.Builder.getInt32(0);
4662 }
4663
4664 // No teams associated with the directive.
4665 return nullptr;
4666}
4667
Samuel Antao86ace552016-04-27 22:40:57 +00004668namespace {
4669// \brief Utility to handle information from clauses associated with a given
4670// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
4671// It provides a convenient interface to obtain the information and generate
4672// code for that information.
4673class MappableExprsHandler {
4674public:
4675 /// \brief Values for bit flags used to specify the mapping type for
4676 /// offloading.
4677 enum OpenMPOffloadMappingFlags {
4678 /// \brief Only allocate memory on the device,
4679 OMP_MAP_ALLOC = 0x00,
4680 /// \brief Allocate memory on the device and move data from host to device.
4681 OMP_MAP_TO = 0x01,
4682 /// \brief Allocate memory on the device and move data from device to host.
4683 OMP_MAP_FROM = 0x02,
4684 /// \brief Always perform the requested mapping action on the element, even
4685 /// if it was already mapped before.
4686 OMP_MAP_ALWAYS = 0x04,
4687 /// \brief Decrement the reference count associated with the element without
4688 /// executing any other action.
4689 OMP_MAP_RELEASE = 0x08,
4690 /// \brief Delete the element from the device environment, ignoring the
4691 /// current reference count associated with the element.
4692 OMP_MAP_DELETE = 0x10,
4693 /// \brief The element passed to the device is a pointer.
4694 OMP_MAP_PTR = 0x20,
4695 /// \brief Signal the element as extra, i.e. is not argument to the target
4696 /// region kernel.
4697 OMP_MAP_EXTRA = 0x40,
4698 /// \brief Pass the element to the device by value.
4699 OMP_MAP_BYCOPY = 0x80,
4700 };
4701
4702 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
4703 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
4704
4705private:
4706 /// \brief Directive from where the map clauses were extracted.
4707 const OMPExecutableDirective &Directive;
4708
4709 /// \brief Function the directive is being generated for.
4710 CodeGenFunction &CGF;
4711
4712 llvm::Value *getExprTypeSize(const Expr *E) const {
4713 auto ExprTy = E->getType().getCanonicalType();
4714
4715 // Reference types are ignored for mapping purposes.
4716 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
4717 ExprTy = RefTy->getPointeeType().getCanonicalType();
4718
4719 // Given that an array section is considered a built-in type, we need to
4720 // do the calculation based on the length of the section instead of relying
4721 // on CGF.getTypeSize(E->getType()).
4722 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
4723 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
4724 OAE->getBase()->IgnoreParenImpCasts())
4725 .getCanonicalType();
4726
4727 // If there is no length associated with the expression, that means we
4728 // are using the whole length of the base.
4729 if (!OAE->getLength() && OAE->getColonLoc().isValid())
4730 return CGF.getTypeSize(BaseTy);
4731
4732 llvm::Value *ElemSize;
4733 if (auto *PTy = BaseTy->getAs<PointerType>())
4734 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
4735 else {
4736 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
4737 assert(ATy && "Expecting array type if not a pointer type.");
4738 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
4739 }
4740
4741 // If we don't have a length at this point, that is because we have an
4742 // array section with a single element.
4743 if (!OAE->getLength())
4744 return ElemSize;
4745
4746 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
4747 LengthVal =
4748 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
4749 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
4750 }
4751 return CGF.getTypeSize(ExprTy);
4752 }
4753
4754 /// \brief Return the corresponding bits for a given map clause modifier. Add
4755 /// a flag marking the map as a pointer if requested. Add a flag marking the
4756 /// map as extra, meaning is not an argument of the kernel.
4757 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
4758 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
4759 bool AddExtraFlag) const {
4760 unsigned Bits = 0u;
4761 switch (MapType) {
4762 case OMPC_MAP_alloc:
4763 Bits = OMP_MAP_ALLOC;
4764 break;
4765 case OMPC_MAP_to:
4766 Bits = OMP_MAP_TO;
4767 break;
4768 case OMPC_MAP_from:
4769 Bits = OMP_MAP_FROM;
4770 break;
4771 case OMPC_MAP_tofrom:
4772 Bits = OMP_MAP_TO | OMP_MAP_FROM;
4773 break;
4774 case OMPC_MAP_delete:
4775 Bits = OMP_MAP_DELETE;
4776 break;
4777 case OMPC_MAP_release:
4778 Bits = OMP_MAP_RELEASE;
4779 break;
4780 default:
4781 llvm_unreachable("Unexpected map type!");
4782 break;
4783 }
4784 if (AddPtrFlag)
4785 Bits |= OMP_MAP_PTR;
4786 if (AddExtraFlag)
4787 Bits |= OMP_MAP_EXTRA;
4788 if (MapTypeModifier == OMPC_MAP_always)
4789 Bits |= OMP_MAP_ALWAYS;
4790 return Bits;
4791 }
4792
4793 /// \brief Return true if the provided expression is a final array section. A
4794 /// final array section, is one whose length can't be proved to be one.
4795 bool isFinalArraySectionExpression(const Expr *E) const {
4796 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
4797
4798 // It is not an array section and therefore not a unity-size one.
4799 if (!OASE)
4800 return false;
4801
4802 // An array section with no colon always refer to a single element.
4803 if (OASE->getColonLoc().isInvalid())
4804 return false;
4805
4806 auto *Length = OASE->getLength();
4807
4808 // If we don't have a length we have to check if the array has size 1
4809 // for this dimension. Also, we should always expect a length if the
4810 // base type is pointer.
4811 if (!Length) {
4812 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
4813 OASE->getBase()->IgnoreParenImpCasts())
4814 .getCanonicalType();
4815 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
4816 return ATy->getSize().getSExtValue() != 1;
4817 // If we don't have a constant dimension length, we have to consider
4818 // the current section as having any size, so it is not necessarily
4819 // unitary. If it happen to be unity size, that's user fault.
4820 return true;
4821 }
4822
4823 // Check if the length evaluates to 1.
4824 llvm::APSInt ConstLength;
4825 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
4826 return true; // Can have more that size 1.
4827
4828 return ConstLength.getSExtValue() != 1;
4829 }
4830
4831 /// \brief Generate the base pointers, section pointers, sizes and map type
4832 /// bits for the provided map type, map modifier, and expression components.
4833 /// \a IsFirstComponent should be set to true if the provided set of
4834 /// components is the first associated with a capture.
4835 void generateInfoForComponentList(
4836 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
4837 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
4838 MapValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
4839 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
4840 bool IsFirstComponentList) const {
4841
4842 // The following summarizes what has to be generated for each map and the
4843 // types bellow. The generated information is expressed in this order:
4844 // base pointer, section pointer, size, flags
4845 // (to add to the ones that come from the map type and modifier).
4846 //
4847 // double d;
4848 // int i[100];
4849 // float *p;
4850 //
4851 // struct S1 {
4852 // int i;
4853 // float f[50];
4854 // }
4855 // struct S2 {
4856 // int i;
4857 // float f[50];
4858 // S1 s;
4859 // double *p;
4860 // struct S2 *ps;
4861 // }
4862 // S2 s;
4863 // S2 *ps;
4864 //
4865 // map(d)
4866 // &d, &d, sizeof(double), noflags
4867 //
4868 // map(i)
4869 // &i, &i, 100*sizeof(int), noflags
4870 //
4871 // map(i[1:23])
4872 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
4873 //
4874 // map(p)
4875 // &p, &p, sizeof(float*), noflags
4876 //
4877 // map(p[1:24])
4878 // p, &p[1], 24*sizeof(float), noflags
4879 //
4880 // map(s)
4881 // &s, &s, sizeof(S2), noflags
4882 //
4883 // map(s.i)
4884 // &s, &(s.i), sizeof(int), noflags
4885 //
4886 // map(s.s.f)
4887 // &s, &(s.i.f), 50*sizeof(int), noflags
4888 //
4889 // map(s.p)
4890 // &s, &(s.p), sizeof(double*), noflags
4891 //
4892 // map(s.p[:22], s.a s.b)
4893 // &s, &(s.p), sizeof(double*), noflags
4894 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
4895 //
4896 // map(s.ps)
4897 // &s, &(s.ps), sizeof(S2*), noflags
4898 //
4899 // map(s.ps->s.i)
4900 // &s, &(s.ps), sizeof(S2*), noflags
4901 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
4902 //
4903 // map(s.ps->ps)
4904 // &s, &(s.ps), sizeof(S2*), noflags
4905 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
4906 //
4907 // map(s.ps->ps->ps)
4908 // &s, &(s.ps), sizeof(S2*), noflags
4909 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
4910 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
4911 //
4912 // map(s.ps->ps->s.f[:22])
4913 // &s, &(s.ps), sizeof(S2*), noflags
4914 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
4915 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
4916 //
4917 // map(ps)
4918 // &ps, &ps, sizeof(S2*), noflags
4919 //
4920 // map(ps->i)
4921 // ps, &(ps->i), sizeof(int), noflags
4922 //
4923 // map(ps->s.f)
4924 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
4925 //
4926 // map(ps->p)
4927 // ps, &(ps->p), sizeof(double*), noflags
4928 //
4929 // map(ps->p[:22])
4930 // ps, &(ps->p), sizeof(double*), noflags
4931 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
4932 //
4933 // map(ps->ps)
4934 // ps, &(ps->ps), sizeof(S2*), noflags
4935 //
4936 // map(ps->ps->s.i)
4937 // ps, &(ps->ps), sizeof(S2*), noflags
4938 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
4939 //
4940 // map(ps->ps->ps)
4941 // ps, &(ps->ps), sizeof(S2*), noflags
4942 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
4943 //
4944 // map(ps->ps->ps->ps)
4945 // ps, &(ps->ps), sizeof(S2*), noflags
4946 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
4947 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
4948 //
4949 // map(ps->ps->ps->s.f[:22])
4950 // ps, &(ps->ps), sizeof(S2*), noflags
4951 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
4952 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
4953 // extra_flag
4954
4955 // Track if the map information being generated is the first for a capture.
4956 bool IsCaptureFirstInfo = IsFirstComponentList;
4957
4958 // Scan the components from the base to the complete expression.
4959 auto CI = Components.rbegin();
4960 auto CE = Components.rend();
4961 auto I = CI;
4962
4963 // Track if the map information being generated is the first for a list of
4964 // components.
4965 bool IsExpressionFirstInfo = true;
4966 llvm::Value *BP = nullptr;
4967
4968 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
4969 // The base is the 'this' pointer. The content of the pointer is going
4970 // to be the base of the field being mapped.
4971 BP = CGF.EmitScalarExpr(ME->getBase());
4972 } else {
4973 // The base is the reference to the variable.
4974 // BP = &Var.
4975 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
4976 .getPointer();
4977
4978 // If the variable is a pointer and is being dereferenced (i.e. is not
4979 // the last component), the base has to be the pointer itself, not his
4980 // reference.
4981 if (I->getAssociatedDeclaration()->getType()->isAnyPointerType() &&
4982 std::next(I) != CE) {
4983 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(
4984 BP, I->getAssociatedDeclaration()->getType());
4985 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
4986 I->getAssociatedDeclaration()
4987 ->getType()
4988 ->getAs<PointerType>())
4989 .getPointer();
4990
4991 // We do not need to generate individual map information for the
4992 // pointer, it can be associated with the combined storage.
4993 ++I;
4994 }
4995 }
4996
4997 for (; I != CE; ++I) {
4998 auto Next = std::next(I);
4999
5000 // We need to generate the addresses and sizes if this is the last
5001 // component, if the component is a pointer or if it is an array section
5002 // whose length can't be proved to be one. If this is a pointer, it
5003 // becomes the base address for the following components.
5004
5005 // A final array section, is one whose length can't be proved to be one.
5006 bool IsFinalArraySection =
5007 isFinalArraySectionExpression(I->getAssociatedExpression());
5008
5009 // Get information on whether the element is a pointer. Have to do a
5010 // special treatment for array sections given that they are built-in
5011 // types.
5012 const auto *OASE =
5013 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5014 bool IsPointer =
5015 (OASE &&
5016 OMPArraySectionExpr::getBaseOriginalType(OASE)
5017 .getCanonicalType()
5018 ->isAnyPointerType()) ||
5019 I->getAssociatedExpression()->getType()->isAnyPointerType();
5020
5021 if (Next == CE || IsPointer || IsFinalArraySection) {
5022
5023 // If this is not the last component, we expect the pointer to be
5024 // associated with an array expression or member expression.
5025 assert((Next == CE ||
5026 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5027 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5028 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5029 "Unexpected expression");
5030
5031 // Save the base we are currently using.
5032 BasePointers.push_back(BP);
5033
5034 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5035 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5036
5037 Pointers.push_back(LB);
5038 Sizes.push_back(Size);
5039 // We need to add a pointer flag for each map that comes from the the
5040 // same expression except for the first one. We need to add the extra
5041 // flag for each map that relates with the current capture, except for
5042 // the first one (there is a set of entries for each capture).
5043 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5044 !IsExpressionFirstInfo,
5045 !IsCaptureFirstInfo));
5046
5047 // If we have a final array section, we are done with this expression.
5048 if (IsFinalArraySection)
5049 break;
5050
5051 // The pointer becomes the base for the next element.
5052 if (Next != CE)
5053 BP = LB;
5054
5055 IsExpressionFirstInfo = false;
5056 IsCaptureFirstInfo = false;
5057 continue;
5058 }
5059 }
5060 }
5061
5062public:
5063 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
5064 : Directive(Dir), CGF(CGF) {}
5065
5066 /// \brief Generate all the base pointers, section pointers, sizes and map
5067 /// types for the extracted mappable expressions.
5068 void generateAllInfo(MapValuesArrayTy &BasePointers,
5069 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5070 MapFlagsArrayTy &Types) const {
5071 BasePointers.clear();
5072 Pointers.clear();
5073 Sizes.clear();
5074 Types.clear();
5075
5076 struct MapInfo {
5077 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
5078 OpenMPMapClauseKind MapType;
5079 OpenMPMapClauseKind MapTypeModifier;
5080 };
5081
5082 // We have to process the component lists that relate with the same
5083 // declaration in a single chunk so that we can generate the map flags
5084 // correctly. Therefore, we organize all lists in a map.
5085 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
5086 for (auto *C : Directive.getClausesOfKind<OMPMapClause>())
5087 for (auto L : C->component_lists()) {
5088 const ValueDecl *VD =
5089 L.first ? cast<ValueDecl>(L.first->getCanonicalDecl()) : nullptr;
5090 Info[VD].push_back(
5091 {L.second, C->getMapType(), C->getMapTypeModifier()});
5092 }
5093
5094 for (auto &M : Info) {
5095 // We need to know when we generate information for the first component
5096 // associated with a capture, because the mapping flags depend on it.
5097 bool IsFirstComponentList = true;
5098 for (MapInfo &L : M.second) {
5099 assert(!L.Components.empty() &&
5100 "Not expecting declaration with no component lists.");
5101 generateInfoForComponentList(L.MapType, L.MapTypeModifier, L.Components,
5102 BasePointers, Pointers, Sizes, Types,
5103 IsFirstComponentList);
5104 IsFirstComponentList = false;
5105 }
5106 }
5107 }
5108
5109 /// \brief Generate the base pointers, section pointers, sizes and map types
5110 /// associated to a given capture.
5111 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
5112 MapValuesArrayTy &BasePointers,
5113 MapValuesArrayTy &Pointers,
5114 MapValuesArrayTy &Sizes,
5115 MapFlagsArrayTy &Types) const {
5116 assert(!Cap->capturesVariableArrayType() &&
5117 "Not expecting to generate map info for a variable array type!");
5118
5119 BasePointers.clear();
5120 Pointers.clear();
5121 Sizes.clear();
5122 Types.clear();
5123
5124 const ValueDecl *VD =
5125 Cap->capturesThis()
5126 ? nullptr
5127 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5128
5129 // We need to know when we generating information for the first component
5130 // associated with a capture, because the mapping flags depend on it.
5131 bool IsFirstComponentList = true;
5132 for (auto *C : Directive.getClausesOfKind<OMPMapClause>())
5133 for (auto L : C->decl_component_lists(VD)) {
5134 assert(L.first == VD &&
5135 "We got information for the wrong declaration??");
5136 assert(!L.second.empty() &&
5137 "Not expecting declaration with no component lists.");
5138 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5139 L.second, BasePointers, Pointers, Sizes,
5140 Types, IsFirstComponentList);
5141 IsFirstComponentList = false;
5142 }
5143
5144 return;
5145 }
5146};
Samuel Antaodf158d52016-04-27 22:58:19 +00005147
5148enum OpenMPOffloadingReservedDeviceIDs {
5149 /// \brief Device ID if the device was not defined, runtime should get it
5150 /// from environment variables in the spec.
5151 OMP_DEVICEID_UNDEF = -1,
5152};
5153} // anonymous namespace
5154
5155/// \brief Emit the arrays used to pass the captures and map information to the
5156/// offloading runtime library. If there is no map or capture information,
5157/// return nullptr by reference.
5158static void
5159emitOffloadingArrays(CodeGenFunction &CGF, llvm::Value *&BasePointersArray,
5160 llvm::Value *&PointersArray, llvm::Value *&SizesArray,
5161 llvm::Value *&MapTypesArray,
5162 MappableExprsHandler::MapValuesArrayTy &BasePointers,
5163 MappableExprsHandler::MapValuesArrayTy &Pointers,
5164 MappableExprsHandler::MapValuesArrayTy &Sizes,
5165 MappableExprsHandler::MapFlagsArrayTy &MapTypes) {
5166 auto &CGM = CGF.CGM;
5167 auto &Ctx = CGF.getContext();
5168
5169 BasePointersArray = PointersArray = SizesArray = MapTypesArray = nullptr;
5170
5171 if (unsigned PointerNumVal = BasePointers.size()) {
5172 // Detect if we have any capture size requiring runtime evaluation of the
5173 // size so that a constant array could be eventually used.
5174 bool hasRuntimeEvaluationCaptureSize = false;
5175 for (auto *S : Sizes)
5176 if (!isa<llvm::Constant>(S)) {
5177 hasRuntimeEvaluationCaptureSize = true;
5178 break;
5179 }
5180
5181 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
5182 QualType PointerArrayType =
5183 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5184 /*IndexTypeQuals=*/0);
5185
5186 BasePointersArray =
5187 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
5188 PointersArray =
5189 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5190
5191 // If we don't have any VLA types or other types that require runtime
5192 // evaluation, we can use a constant array for the map sizes, otherwise we
5193 // need to fill up the arrays as we do for the pointers.
5194 if (hasRuntimeEvaluationCaptureSize) {
5195 QualType SizeArrayType = Ctx.getConstantArrayType(
5196 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5197 /*IndexTypeQuals=*/0);
5198 SizesArray =
5199 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5200 } else {
5201 // We expect all the sizes to be constant, so we collect them to create
5202 // a constant array.
5203 SmallVector<llvm::Constant *, 16> ConstSizes;
5204 for (auto S : Sizes)
5205 ConstSizes.push_back(cast<llvm::Constant>(S));
5206
5207 auto *SizesArrayInit = llvm::ConstantArray::get(
5208 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5209 auto *SizesArrayGbl = new llvm::GlobalVariable(
5210 CGM.getModule(), SizesArrayInit->getType(),
5211 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5212 SizesArrayInit, ".offload_sizes");
5213 SizesArrayGbl->setUnnamedAddr(true);
5214 SizesArray = SizesArrayGbl;
5215 }
5216
5217 // The map types are always constant so we don't need to generate code to
5218 // fill arrays. Instead, we create an array constant.
5219 llvm::Constant *MapTypesArrayInit =
5220 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5221 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5222 CGM.getModule(), MapTypesArrayInit->getType(),
5223 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5224 MapTypesArrayInit, ".offload_maptypes");
5225 MapTypesArrayGbl->setUnnamedAddr(true);
5226 MapTypesArray = MapTypesArrayGbl;
5227
5228 for (unsigned i = 0; i < PointerNumVal; ++i) {
5229 llvm::Value *BPVal = BasePointers[i];
5230 if (BPVal->getType()->isPointerTy())
5231 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
5232 else {
5233 assert(BPVal->getType()->isIntegerTy() &&
5234 "If not a pointer, the value type must be an integer.");
5235 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
5236 }
5237 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
5238 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), BasePointersArray,
5239 0, i);
5240 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5241 CGF.Builder.CreateStore(BPVal, BPAddr);
5242
5243 llvm::Value *PVal = Pointers[i];
5244 if (PVal->getType()->isPointerTy())
5245 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
5246 else {
5247 assert(PVal->getType()->isIntegerTy() &&
5248 "If not a pointer, the value type must be an integer.");
5249 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
5250 }
5251 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
5252 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray, 0,
5253 i);
5254 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5255 CGF.Builder.CreateStore(PVal, PAddr);
5256
5257 if (hasRuntimeEvaluationCaptureSize) {
5258 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
5259 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
5260 /*Idx0=*/0,
5261 /*Idx1=*/i);
5262 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5263 CGF.Builder.CreateStore(
5264 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5265 SAddr);
5266 }
5267 }
5268 }
5269}
5270/// \brief Emit the arguments to be passed to the runtime library based on the
5271/// arrays of pointers, sizes and map types.
5272static void emitOffloadingArraysArgument(
5273 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5274 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
5275 llvm::Value *&MapTypesArrayArg, llvm::Value *BasePointersArray,
5276 llvm::Value *PointersArray, llvm::Value *SizesArray,
5277 llvm::Value *MapTypesArray, unsigned NumElems) {
5278 auto &CGM = CGF.CGM;
5279 if (NumElems) {
5280 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5281 llvm::ArrayType::get(CGM.VoidPtrTy, NumElems), BasePointersArray,
5282 /*Idx0=*/0, /*Idx1=*/0);
5283 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5284 llvm::ArrayType::get(CGM.VoidPtrTy, NumElems), PointersArray,
5285 /*Idx0=*/0,
5286 /*Idx1=*/0);
5287 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5288 llvm::ArrayType::get(CGM.SizeTy, NumElems), SizesArray,
5289 /*Idx0=*/0, /*Idx1=*/0);
5290 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5291 llvm::ArrayType::get(CGM.Int32Ty, NumElems), MapTypesArray,
5292 /*Idx0=*/0,
5293 /*Idx1=*/0);
5294 } else {
5295 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5296 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5297 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5298 MapTypesArrayArg =
5299 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
5300 }
Samuel Antao86ace552016-04-27 22:40:57 +00005301}
5302
Samuel Antaobed3c462015-10-02 16:14:20 +00005303void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
5304 const OMPExecutableDirective &D,
5305 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00005306 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00005307 const Expr *IfCond, const Expr *Device,
5308 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005309 if (!CGF.HaveInsertPoint())
5310 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00005311
Samuel Antaoee8fb302016-01-06 13:42:12 +00005312 assert(OutlinedFn && "Invalid outlined function!");
5313
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005314 auto &Ctx = CGF.getContext();
5315
Samuel Antao86ace552016-04-27 22:40:57 +00005316 // Fill up the arrays with all the captured variables.
5317 MappableExprsHandler::MapValuesArrayTy KernelArgs;
5318 MappableExprsHandler::MapValuesArrayTy BasePointers;
5319 MappableExprsHandler::MapValuesArrayTy Pointers;
5320 MappableExprsHandler::MapValuesArrayTy Sizes;
5321 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00005322
Samuel Antao86ace552016-04-27 22:40:57 +00005323 MappableExprsHandler::MapValuesArrayTy CurBasePointers;
5324 MappableExprsHandler::MapValuesArrayTy CurPointers;
5325 MappableExprsHandler::MapValuesArrayTy CurSizes;
5326 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
5327
5328 // Get map clause information.
5329 MappableExprsHandler MCHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005330
5331 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5332 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00005333 auto CV = CapturedVars.begin();
5334 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
5335 CE = CS.capture_end();
5336 CI != CE; ++CI, ++RI, ++CV) {
5337 StringRef Name;
5338 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00005339
Samuel Antao86ace552016-04-27 22:40:57 +00005340 CurBasePointers.clear();
5341 CurPointers.clear();
5342 CurSizes.clear();
5343 CurMapTypes.clear();
5344
5345 // VLA sizes are passed to the outlined region by copy and do not have map
5346 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00005347 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00005348 CurBasePointers.push_back(*CV);
5349 CurPointers.push_back(*CV);
5350 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005351 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao86ace552016-04-27 22:40:57 +00005352 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_BYCOPY);
Samuel Antaobed3c462015-10-02 16:14:20 +00005353 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00005354 // If we have any information in the map clause, we use it, otherwise we
5355 // just do a default mapping.
5356 MCHandler.generateInfoForCapture(CI, CurBasePointers, CurPointers,
5357 CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00005358
Samuel Antao86ace552016-04-27 22:40:57 +00005359 if (CurBasePointers.empty()) {
5360 // Do the default mapping.
5361 if (CI->capturesThis()) {
5362 CurBasePointers.push_back(*CV);
5363 CurPointers.push_back(*CV);
5364 const PointerType *PtrTy =
5365 cast<PointerType>(RI->getType().getTypePtr());
5366 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5367 // Default map type.
5368 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_TO |
5369 MappableExprsHandler::OMP_MAP_FROM);
5370 } else if (CI->capturesVariableByCopy()) {
5371 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_BYCOPY);
5372 if (!RI->getType()->isAnyPointerType()) {
5373 // If the field is not a pointer, we need to save the actual value
5374 // and
5375 // load it as a void pointer.
5376 auto DstAddr = CGF.CreateMemTemp(
5377 Ctx.getUIntPtrType(),
5378 Twine(CI->getCapturedVar()->getName()) + ".casted");
5379 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
5380
5381 auto *SrcAddrVal = CGF.EmitScalarConversion(
5382 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
5383 Ctx.getPointerType(RI->getType()), SourceLocation());
5384 LValue SrcLV =
5385 CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
5386
5387 // Store the value using the source type pointer.
5388 CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
5389
5390 // Load the value using the destination type pointer.
5391 CurBasePointers.push_back(
5392 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal());
5393 CurPointers.push_back(CurBasePointers.back());
5394 } else {
5395 CurBasePointers.push_back(*CV);
5396 CurPointers.push_back(*CV);
5397 }
5398 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
5399 } else {
5400 assert(CI->capturesVariable() && "Expected captured reference.");
5401 CurBasePointers.push_back(*CV);
5402 CurPointers.push_back(*CV);
5403
5404 const ReferenceType *PtrTy =
5405 cast<ReferenceType>(RI->getType().getTypePtr());
5406 QualType ElementType = PtrTy->getPointeeType();
5407 CurSizes.push_back(CGF.getTypeSize(ElementType));
5408 // The default map type for a scalar/complex type is 'to' because by
5409 // default the value doesn't have to be retrieved. For an aggregate
5410 // type,
5411 // the default is 'tofrom'.
5412 CurMapTypes.push_back(ElementType->isAggregateType()
5413 ? (MappableExprsHandler::OMP_MAP_TO |
5414 MappableExprsHandler::OMP_MAP_FROM)
5415 : MappableExprsHandler::OMP_MAP_TO);
5416 }
5417 }
Samuel Antaobed3c462015-10-02 16:14:20 +00005418 }
Samuel Antao86ace552016-04-27 22:40:57 +00005419 // We expect to have at least an element of information for this capture.
5420 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
5421 assert(CurBasePointers.size() == CurPointers.size() &&
5422 CurBasePointers.size() == CurSizes.size() &&
5423 CurBasePointers.size() == CurMapTypes.size() &&
5424 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005425
Samuel Antao86ace552016-04-27 22:40:57 +00005426 // The kernel args are always the first elements of the base pointers
5427 // associated with a capture.
5428 KernelArgs.push_back(CurBasePointers.front());
5429 // We need to append the results of this capture to what we already have.
5430 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
5431 Pointers.append(CurPointers.begin(), CurPointers.end());
5432 Sizes.append(CurSizes.begin(), CurSizes.end());
5433 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00005434 }
5435
5436 // Keep track on whether the host function has to be executed.
5437 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005438 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005439 auto OffloadError = CGF.MakeAddrLValue(
5440 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
5441 OffloadErrorQType);
5442 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
5443 OffloadError);
5444
5445 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antaodf158d52016-04-27 22:58:19 +00005446 auto &&ThenGen = [&Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
5447 OutlinedFnID, OffloadError, OffloadErrorQType,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005448 &D](CodeGenFunction &CGF, PrePostActionTy &) {
5449 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00005450 // Emit the offloading arrays.
Samuel Antaobed3c462015-10-02 16:14:20 +00005451 llvm::Value *BasePointersArray;
5452 llvm::Value *PointersArray;
5453 llvm::Value *SizesArray;
5454 llvm::Value *MapTypesArray;
Samuel Antaodf158d52016-04-27 22:58:19 +00005455 emitOffloadingArrays(CGF, BasePointersArray, PointersArray, SizesArray,
5456 MapTypesArray, BasePointers, Pointers, Sizes,
5457 MapTypes);
5458 emitOffloadingArraysArgument(CGF, BasePointersArray, PointersArray,
5459 SizesArray, MapTypesArray, BasePointersArray,
5460 PointersArray, SizesArray, MapTypesArray,
5461 BasePointers.size());
Samuel Antaobed3c462015-10-02 16:14:20 +00005462
5463 // On top of the arrays that were filled up, the target offloading call
5464 // takes as arguments the device id as well as the host pointer. The host
5465 // pointer is used by the runtime library to identify the current target
5466 // region, so it only has to be unique and not necessarily point to
5467 // anything. It could be the pointer to the outlined function that
5468 // implements the target region, but we aren't using that so that the
5469 // compiler doesn't need to keep that, and could therefore inline the host
5470 // function if proven worthwhile during optimization.
5471
Samuel Antaoee8fb302016-01-06 13:42:12 +00005472 // From this point on, we need to have an ID of the target region defined.
5473 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005474
5475 // Emit device ID if any.
5476 llvm::Value *DeviceID;
5477 if (Device)
5478 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005479 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005480 else
5481 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
5482
Samuel Antaodf158d52016-04-27 22:58:19 +00005483 // Emit the number of elements in the offloading arrays.
5484 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
5485
Samuel Antaob68e2db2016-03-03 16:20:23 +00005486 // Return value of the runtime offloading call.
5487 llvm::Value *Return;
5488
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005489 auto *NumTeams = emitNumTeamsClauseForTargetDirective(RT, CGF, D);
5490 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005491
5492 // If we have NumTeams defined this means that we have an enclosed teams
5493 // region. Therefore we also expect to have ThreadLimit defined. These two
5494 // values should be defined in the presence of a teams directive, regardless
5495 // of having any clauses associated. If the user is using teams but no
5496 // clauses, these two values will be the default that should be passed to
5497 // the runtime library - a 32-bit integer with the value zero.
5498 if (NumTeams) {
5499 assert(ThreadLimit && "Thread limit expression should be available along "
5500 "with number of teams.");
5501 llvm::Value *OffloadingArgs[] = {
5502 DeviceID, OutlinedFnID, PointerNum,
5503 BasePointersArray, PointersArray, SizesArray,
5504 MapTypesArray, NumTeams, ThreadLimit};
5505 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005506 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005507 } else {
5508 llvm::Value *OffloadingArgs[] = {
5509 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
5510 PointersArray, SizesArray, MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005511 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00005512 OffloadingArgs);
5513 }
Samuel Antaobed3c462015-10-02 16:14:20 +00005514
5515 CGF.EmitStoreOfScalar(Return, OffloadError);
5516 };
5517
Samuel Antaoee8fb302016-01-06 13:42:12 +00005518 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005519 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
5520 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00005521 OffloadError);
5522 };
5523
5524 // If we have a target function ID it means that we need to support
5525 // offloading, otherwise, just execute on the host. We need to execute on host
5526 // regardless of the conditional in the if clause if, e.g., the user do not
5527 // specify target triples.
5528 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005529 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00005530 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005531 else {
5532 RegionCodeGenTy ThenRCG(ThenGen);
5533 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005534 }
5535 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005536 RegionCodeGenTy ElseRCG(ElseGen);
5537 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005538 }
Samuel Antaobed3c462015-10-02 16:14:20 +00005539
5540 // Check the error code and execute the host version if required.
5541 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
5542 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
5543 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
5544 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
5545 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
5546
5547 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00005548 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00005549 CGF.EmitBranch(OffloadContBlock);
5550
5551 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005552}
Samuel Antaoee8fb302016-01-06 13:42:12 +00005553
5554void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
5555 StringRef ParentName) {
5556 if (!S)
5557 return;
5558
5559 // If we find a OMP target directive, codegen the outline function and
5560 // register the result.
5561 // FIXME: Add other directives with target when they become supported.
5562 bool isTargetDirective = isa<OMPTargetDirective>(S);
5563
5564 if (isTargetDirective) {
5565 auto *E = cast<OMPExecutableDirective>(S);
5566 unsigned DeviceID;
5567 unsigned FileID;
5568 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005569 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005570 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005571
5572 // Is this a target region that should not be emitted as an entry point? If
5573 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00005574 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
5575 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00005576 return;
5577
5578 llvm::Function *Fn;
5579 llvm::Constant *Addr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005580 std::tie(Fn, Addr) =
5581 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
5582 CGM, cast<OMPTargetDirective>(*E), ParentName,
5583 /*isOffloadEntry=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005584 assert(Fn && Addr && "Target region emission failed.");
5585 return;
5586 }
5587
5588 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
5589 if (!E->getAssociatedStmt())
5590 return;
5591
5592 scanForTargetRegionsFunctions(
5593 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
5594 ParentName);
5595 return;
5596 }
5597
5598 // If this is a lambda function, look into its body.
5599 if (auto *L = dyn_cast<LambdaExpr>(S))
5600 S = L->getBody();
5601
5602 // Keep looking for target regions recursively.
5603 for (auto *II : S->children())
5604 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005605}
5606
5607bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
5608 auto &FD = *cast<FunctionDecl>(GD.getDecl());
5609
5610 // If emitting code for the host, we do not process FD here. Instead we do
5611 // the normal code generation.
5612 if (!CGM.getLangOpts().OpenMPIsDevice)
5613 return false;
5614
5615 // Try to detect target regions in the function.
5616 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
5617
5618 // We should not emit any function othen that the ones created during the
5619 // scanning. Therefore, we signal that this function is completely dealt
5620 // with.
5621 return true;
5622}
5623
5624bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
5625 if (!CGM.getLangOpts().OpenMPIsDevice)
5626 return false;
5627
5628 // Check if there are Ctors/Dtors in this declaration and look for target
5629 // regions in it. We use the complete variant to produce the kernel name
5630 // mangling.
5631 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
5632 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
5633 for (auto *Ctor : RD->ctors()) {
5634 StringRef ParentName =
5635 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
5636 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
5637 }
5638 auto *Dtor = RD->getDestructor();
5639 if (Dtor) {
5640 StringRef ParentName =
5641 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
5642 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
5643 }
5644 }
5645
5646 // If we are in target mode we do not emit any global (declare target is not
5647 // implemented yet). Therefore we signal that GD was processed in this case.
5648 return true;
5649}
5650
5651bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
5652 auto *VD = GD.getDecl();
5653 if (isa<FunctionDecl>(VD))
5654 return emitTargetFunctions(GD);
5655
5656 return emitTargetGlobalVariable(GD);
5657}
5658
5659llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
5660 // If we have offloading in the current module, we need to emit the entries
5661 // now and register the offloading descriptor.
5662 createOffloadEntriesAndInfoMetadata();
5663
5664 // Create and register the offloading binary descriptors. This is the main
5665 // entity that captures all the information about offloading in the current
5666 // compilation unit.
5667 return createOffloadingBinaryDescriptorRegistration();
5668}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00005669
5670void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
5671 const OMPExecutableDirective &D,
5672 SourceLocation Loc,
5673 llvm::Value *OutlinedFn,
5674 ArrayRef<llvm::Value *> CapturedVars) {
5675 if (!CGF.HaveInsertPoint())
5676 return;
5677
5678 auto *RTLoc = emitUpdateLocation(CGF, Loc);
5679 CodeGenFunction::RunCleanupsScope Scope(CGF);
5680
5681 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
5682 llvm::Value *Args[] = {
5683 RTLoc,
5684 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
5685 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
5686 llvm::SmallVector<llvm::Value *, 16> RealArgs;
5687 RealArgs.append(std::begin(Args), std::end(Args));
5688 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
5689
5690 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
5691 CGF.EmitRuntimeCall(RTLFn, RealArgs);
5692}
5693
5694void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00005695 const Expr *NumTeams,
5696 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00005697 SourceLocation Loc) {
5698 if (!CGF.HaveInsertPoint())
5699 return;
5700
5701 auto *RTLoc = emitUpdateLocation(CGF, Loc);
5702
Carlo Bertollic6872252016-04-04 15:55:02 +00005703 llvm::Value *NumTeamsVal =
5704 (NumTeams)
5705 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
5706 CGF.CGM.Int32Ty, /* isSigned = */ true)
5707 : CGF.Builder.getInt32(0);
5708
5709 llvm::Value *ThreadLimitVal =
5710 (ThreadLimit)
5711 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
5712 CGF.CGM.Int32Ty, /* isSigned = */ true)
5713 : CGF.Builder.getInt32(0);
5714
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00005715 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00005716 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
5717 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00005718 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
5719 PushNumTeamsArgs);
5720}
Samuel Antaodf158d52016-04-27 22:58:19 +00005721
5722void CGOpenMPRuntime::emitTargetDataCalls(CodeGenFunction &CGF,
5723 const OMPExecutableDirective &D,
5724 const Expr *IfCond,
5725 const Expr *Device,
5726 const RegionCodeGenTy &CodeGen) {
5727
5728 if (!CGF.HaveInsertPoint())
5729 return;
5730
5731 llvm::Value *BasePointersArray = nullptr;
5732 llvm::Value *PointersArray = nullptr;
5733 llvm::Value *SizesArray = nullptr;
5734 llvm::Value *MapTypesArray = nullptr;
5735 unsigned NumOfPtrs = 0;
5736
5737 // Generate the code for the opening of the data environment. Capture all the
5738 // arguments of the runtime call by reference because they are used in the
5739 // closing of the region.
5740 auto &&BeginThenGen = [&D, &CGF, &BasePointersArray, &PointersArray,
5741 &SizesArray, &MapTypesArray, Device,
5742 &NumOfPtrs](CodeGenFunction &CGF, PrePostActionTy &) {
5743 // Fill up the arrays with all the mapped variables.
5744 MappableExprsHandler::MapValuesArrayTy BasePointers;
5745 MappableExprsHandler::MapValuesArrayTy Pointers;
5746 MappableExprsHandler::MapValuesArrayTy Sizes;
5747 MappableExprsHandler::MapFlagsArrayTy MapTypes;
5748
5749 // Get map clause information.
5750 MappableExprsHandler MCHandler(D, CGF);
5751 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
5752 NumOfPtrs = BasePointers.size();
5753
5754 // Fill up the arrays and create the arguments.
5755 emitOffloadingArrays(CGF, BasePointersArray, PointersArray, SizesArray,
5756 MapTypesArray, BasePointers, Pointers, Sizes,
5757 MapTypes);
5758
5759 llvm::Value *BasePointersArrayArg = nullptr;
5760 llvm::Value *PointersArrayArg = nullptr;
5761 llvm::Value *SizesArrayArg = nullptr;
5762 llvm::Value *MapTypesArrayArg = nullptr;
5763 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
5764 SizesArrayArg, MapTypesArrayArg,
5765 BasePointersArray, PointersArray, SizesArray,
5766 MapTypesArray, NumOfPtrs);
5767
5768 // Emit device ID if any.
5769 llvm::Value *DeviceID = nullptr;
5770 if (Device)
5771 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
5772 CGF.Int32Ty, /*isSigned=*/true);
5773 else
5774 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
5775
5776 // Emit the number of elements in the offloading arrays.
5777 auto *PointerNum = CGF.Builder.getInt32(NumOfPtrs);
5778
5779 llvm::Value *OffloadingArgs[] = {
5780 DeviceID, PointerNum, BasePointersArrayArg,
5781 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
5782 auto &RT = CGF.CGM.getOpenMPRuntime();
5783 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
5784 OffloadingArgs);
5785 };
5786
5787 // Generate code for the closing of the data region.
5788 auto &&EndThenGen = [&CGF, &BasePointersArray, &PointersArray, &SizesArray,
5789 &MapTypesArray, Device,
5790 &NumOfPtrs](CodeGenFunction &CGF, PrePostActionTy &) {
5791 assert(BasePointersArray && PointersArray && SizesArray && MapTypesArray &&
5792 NumOfPtrs && "Invalid data environment closing arguments.");
5793
5794 llvm::Value *BasePointersArrayArg = nullptr;
5795 llvm::Value *PointersArrayArg = nullptr;
5796 llvm::Value *SizesArrayArg = nullptr;
5797 llvm::Value *MapTypesArrayArg = nullptr;
5798 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
5799 SizesArrayArg, MapTypesArrayArg,
5800 BasePointersArray, PointersArray, SizesArray,
5801 MapTypesArray, NumOfPtrs);
5802
5803 // Emit device ID if any.
5804 llvm::Value *DeviceID = nullptr;
5805 if (Device)
5806 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
5807 CGF.Int32Ty, /*isSigned=*/true);
5808 else
5809 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
5810
5811 // Emit the number of elements in the offloading arrays.
5812 auto *PointerNum = CGF.Builder.getInt32(NumOfPtrs);
5813
5814 llvm::Value *OffloadingArgs[] = {
5815 DeviceID, PointerNum, BasePointersArrayArg,
5816 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
5817 auto &RT = CGF.CGM.getOpenMPRuntime();
5818 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
5819 OffloadingArgs);
5820 };
5821
5822 // In the event we get an if clause, we don't have to take any action on the
5823 // else side.
5824 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
5825
5826 if (IfCond) {
5827 emitOMPIfClause(CGF, IfCond, BeginThenGen, ElseGen);
5828 } else {
5829 RegionCodeGenTy BeginThenRCG(BeginThenGen);
5830 BeginThenRCG(CGF);
5831 }
5832
5833 CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data, CodeGen);
5834
5835 if (IfCond) {
5836 emitOMPIfClause(CGF, IfCond, EndThenGen, ElseGen);
5837 } else {
5838 RegionCodeGenTy EndThenRCG(EndThenGen);
5839 EndThenRCG(CGF);
5840 }
5841}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00005842
5843void CGOpenMPRuntime::emitTargetEnterDataCall(CodeGenFunction &CGF,
5844 const OMPExecutableDirective &D,
5845 const Expr *IfCond,
5846 const Expr *Device) {
5847 if (!CGF.HaveInsertPoint())
5848 return;
5849
5850 // Generate the code for the opening of the data environment.
5851 auto &&ThenGen = [&D, &CGF, Device](CodeGenFunction &CGF, PrePostActionTy &) {
5852 // Fill up the arrays with all the mapped variables.
5853 MappableExprsHandler::MapValuesArrayTy BasePointers;
5854 MappableExprsHandler::MapValuesArrayTy Pointers;
5855 MappableExprsHandler::MapValuesArrayTy Sizes;
5856 MappableExprsHandler::MapFlagsArrayTy MapTypes;
5857
5858 // Get map clause information.
5859 MappableExprsHandler MCHandler(D, CGF);
5860 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
5861
5862 llvm::Value *BasePointersArrayArg = nullptr;
5863 llvm::Value *PointersArrayArg = nullptr;
5864 llvm::Value *SizesArrayArg = nullptr;
5865 llvm::Value *MapTypesArrayArg = nullptr;
5866
5867 // Fill up the arrays and create the arguments.
5868 emitOffloadingArrays(CGF, BasePointersArrayArg, PointersArrayArg,
5869 SizesArrayArg, MapTypesArrayArg, BasePointers,
5870 Pointers, Sizes, MapTypes);
5871 emitOffloadingArraysArgument(
5872 CGF, BasePointersArrayArg, PointersArrayArg, SizesArrayArg,
5873 MapTypesArrayArg, BasePointersArrayArg, PointersArrayArg, SizesArrayArg,
5874 MapTypesArrayArg, BasePointers.size());
5875
5876 // Emit device ID if any.
5877 llvm::Value *DeviceID = nullptr;
5878 if (Device)
5879 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
5880 CGF.Int32Ty, /*isSigned=*/true);
5881 else
5882 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
5883
5884 // Emit the number of elements in the offloading arrays.
5885 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
5886
5887 llvm::Value *OffloadingArgs[] = {
5888 DeviceID, PointerNum, BasePointersArrayArg,
5889 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
5890 auto &RT = CGF.CGM.getOpenMPRuntime();
5891 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
5892 OffloadingArgs);
5893 };
5894
5895 // In the event we get an if clause, we don't have to take any action on the
5896 // else side.
5897 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
5898
5899 if (IfCond) {
5900 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
5901 } else {
5902 RegionCodeGenTy ThenGenRCG(ThenGen);
5903 ThenGenRCG(CGF);
5904 }
5905}