blob: dd07d0f34339ec7826a144fca29887c698c73522 [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 Bataev9ebd7422016-05-10 09:57:36 +0000503 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
504 /// Set if the monotonic schedule modifier was present.
505 OMP_sch_modifier_monotonic = (1 << 29),
506 /// Set if the nonmonotonic schedule modifier was present.
507 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000508};
509
510enum OpenMPRTLFunction {
511 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
512 /// kmpc_micro microtask, ...);
513 OMPRTL__kmpc_fork_call,
514 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
515 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
516 OMPRTL__kmpc_threadprivate_cached,
517 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
518 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
519 OMPRTL__kmpc_threadprivate_register,
520 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
521 OMPRTL__kmpc_global_thread_num,
522 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
523 // kmp_critical_name *crit);
524 OMPRTL__kmpc_critical,
525 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
526 // global_tid, kmp_critical_name *crit, uintptr_t hint);
527 OMPRTL__kmpc_critical_with_hint,
528 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
529 // kmp_critical_name *crit);
530 OMPRTL__kmpc_end_critical,
531 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
532 // global_tid);
533 OMPRTL__kmpc_cancel_barrier,
534 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
535 OMPRTL__kmpc_barrier,
536 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
537 OMPRTL__kmpc_for_static_fini,
538 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
539 // global_tid);
540 OMPRTL__kmpc_serialized_parallel,
541 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
542 // global_tid);
543 OMPRTL__kmpc_end_serialized_parallel,
544 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
545 // kmp_int32 num_threads);
546 OMPRTL__kmpc_push_num_threads,
547 // Call to void __kmpc_flush(ident_t *loc);
548 OMPRTL__kmpc_flush,
549 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
550 OMPRTL__kmpc_master,
551 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
552 OMPRTL__kmpc_end_master,
553 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
554 // int end_part);
555 OMPRTL__kmpc_omp_taskyield,
556 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
557 OMPRTL__kmpc_single,
558 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
559 OMPRTL__kmpc_end_single,
560 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
561 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
562 // kmp_routine_entry_t *task_entry);
563 OMPRTL__kmpc_omp_task_alloc,
564 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
565 // new_task);
566 OMPRTL__kmpc_omp_task,
567 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
568 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
569 // kmp_int32 didit);
570 OMPRTL__kmpc_copyprivate,
571 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
572 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
573 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
574 OMPRTL__kmpc_reduce,
575 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
576 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
577 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
578 // *lck);
579 OMPRTL__kmpc_reduce_nowait,
580 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
581 // kmp_critical_name *lck);
582 OMPRTL__kmpc_end_reduce,
583 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
584 // kmp_critical_name *lck);
585 OMPRTL__kmpc_end_reduce_nowait,
586 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
587 // kmp_task_t * new_task);
588 OMPRTL__kmpc_omp_task_begin_if0,
589 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
590 // kmp_task_t * new_task);
591 OMPRTL__kmpc_omp_task_complete_if0,
592 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
593 OMPRTL__kmpc_ordered,
594 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
595 OMPRTL__kmpc_end_ordered,
596 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
597 // global_tid);
598 OMPRTL__kmpc_omp_taskwait,
599 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
600 OMPRTL__kmpc_taskgroup,
601 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
602 OMPRTL__kmpc_end_taskgroup,
603 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
604 // int proc_bind);
605 OMPRTL__kmpc_push_proc_bind,
606 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
607 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
608 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
609 OMPRTL__kmpc_omp_task_with_deps,
610 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
611 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
612 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
613 OMPRTL__kmpc_omp_wait_deps,
614 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
615 // global_tid, kmp_int32 cncl_kind);
616 OMPRTL__kmpc_cancellationpoint,
617 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
618 // kmp_int32 cncl_kind);
619 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000620 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
621 // kmp_int32 num_teams, kmp_int32 thread_limit);
622 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000623 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
624 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000625 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000626 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
627 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
628 // sched, kmp_uint64 grainsize, void *task_dup);
629 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000630 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
631 // num_dims, struct kmp_dim *dims);
632 OMPRTL__kmpc_doacross_init,
633 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
634 OMPRTL__kmpc_doacross_fini,
635 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
636 // *vec);
637 OMPRTL__kmpc_doacross_post,
638 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
639 // *vec);
640 OMPRTL__kmpc_doacross_wait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000641
642 //
643 // Offloading related calls
644 //
645 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
646 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
647 // *arg_types);
648 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000649 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
650 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
651 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
652 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000653 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
654 OMPRTL__tgt_register_lib,
655 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
656 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000657 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
658 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
659 OMPRTL__tgt_target_data_begin,
660 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
661 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
662 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000663 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
664 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
665 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000666};
667
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000668/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
669/// region.
670class CleanupTy final : public EHScopeStack::Cleanup {
671 PrePostActionTy *Action;
672
673public:
674 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
675 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
676 if (!CGF.HaveInsertPoint())
677 return;
678 Action->Exit(CGF);
679 }
680};
681
Hans Wennborg7eb54642015-09-10 17:07:54 +0000682} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000683
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000684void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
685 CodeGenFunction::RunCleanupsScope Scope(CGF);
686 if (PrePostAction) {
687 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
688 Callback(CodeGen, CGF, *PrePostAction);
689 } else {
690 PrePostActionTy Action;
691 Callback(CodeGen, CGF, Action);
692 }
693}
694
Alexey Bataev18095712014-10-10 12:19:54 +0000695LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000696 return CGF.EmitLoadOfPointerLValue(
697 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
698 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000699}
700
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000701void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000702 if (!CGF.HaveInsertPoint())
703 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000704 // 1.2.2 OpenMP Language Terminology
705 // Structured block - An executable statement with a single entry at the
706 // top and a single exit at the bottom.
707 // The point of exit cannot be a branch out of the structured block.
708 // longjmp() and throw() must not violate the entry/exit criteria.
709 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000710 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000711 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000712}
713
Alexey Bataev62b63b12015-03-10 07:28:44 +0000714LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
715 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000716 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
717 getThreadIDVariable()->getType(),
718 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000719}
720
Alexey Bataev9959db52014-05-06 10:08:46 +0000721CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000722 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000723 IdentTy = llvm::StructType::create(
724 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
725 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000726 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000727 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000728
729 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000730}
731
Alexey Bataev91797552015-03-18 04:13:55 +0000732void CGOpenMPRuntime::clear() {
733 InternalVars.clear();
734}
735
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000736static llvm::Function *
737emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
738 const Expr *CombinerInitializer, const VarDecl *In,
739 const VarDecl *Out, bool IsCombiner) {
740 // void .omp_combiner.(Ty *in, Ty *out);
741 auto &C = CGM.getContext();
742 QualType PtrTy = C.getPointerType(Ty).withRestrict();
743 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000744 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
745 /*Id=*/nullptr, PtrTy);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000746 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
747 /*Id=*/nullptr, PtrTy);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000748 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000749 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000750 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000751 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000752 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
753 auto *Fn = llvm::Function::Create(
754 FnTy, llvm::GlobalValue::InternalLinkage,
755 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
756 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000757 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000758 CodeGenFunction CGF(CGM);
759 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
760 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
761 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
762 CodeGenFunction::OMPPrivateScope Scope(CGF);
763 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
764 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
765 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
766 .getAddress();
767 });
768 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
769 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
770 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
771 .getAddress();
772 });
773 (void)Scope.Privatize();
774 CGF.EmitIgnoredExpr(CombinerInitializer);
775 Scope.ForceCleanup();
776 CGF.FinishFunction();
777 return Fn;
778}
779
780void CGOpenMPRuntime::emitUserDefinedReduction(
781 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
782 if (UDRMap.count(D) > 0)
783 return;
784 auto &C = CGM.getContext();
785 if (!In || !Out) {
786 In = &C.Idents.get("omp_in");
787 Out = &C.Idents.get("omp_out");
788 }
789 llvm::Function *Combiner = emitCombinerOrInitializer(
790 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
791 cast<VarDecl>(D->lookup(Out).front()),
792 /*IsCombiner=*/true);
793 llvm::Function *Initializer = nullptr;
794 if (auto *Init = D->getInitializer()) {
795 if (!Priv || !Orig) {
796 Priv = &C.Idents.get("omp_priv");
797 Orig = &C.Idents.get("omp_orig");
798 }
799 Initializer = emitCombinerOrInitializer(
800 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
801 cast<VarDecl>(D->lookup(Priv).front()),
802 /*IsCombiner=*/false);
803 }
804 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
805 if (CGF) {
806 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
807 Decls.second.push_back(D);
808 }
809}
810
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000811std::pair<llvm::Function *, llvm::Function *>
812CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
813 auto I = UDRMap.find(D);
814 if (I != UDRMap.end())
815 return I->second;
816 emitUserDefinedReduction(/*CGF=*/nullptr, D);
817 return UDRMap.lookup(D);
818}
819
John McCall7f416cc2015-09-08 08:05:57 +0000820// Layout information for ident_t.
821static CharUnits getIdentAlign(CodeGenModule &CGM) {
822 return CGM.getPointerAlign();
823}
824static CharUnits getIdentSize(CodeGenModule &CGM) {
825 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
826 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
827}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000828static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000829 // All the fields except the last are i32, so this works beautifully.
830 return unsigned(Field) * CharUnits::fromQuantity(4);
831}
832static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000833 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000834 const llvm::Twine &Name = "") {
835 auto Offset = getOffsetOfIdentField(Field);
836 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
837}
838
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000839llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000840 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
841 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000842 assert(ThreadIDVar->getType()->isPointerType() &&
843 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000844 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
845 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000846 bool HasCancel = false;
847 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
848 HasCancel = OPD->hasCancel();
849 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
850 HasCancel = OPSD->hasCancel();
851 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
852 HasCancel = OPFD->hasCancel();
853 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
854 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000855 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000856 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000857}
858
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000859llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
860 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000861 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
862 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
863 bool Tied, unsigned &NumberOfParts) {
864 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
865 PrePostActionTy &) {
866 auto *ThreadID = getThreadID(CGF, D.getLocStart());
867 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
868 llvm::Value *TaskArgs[] = {
869 UpLoc, ThreadID,
870 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
871 TaskTVar->getType()->castAs<PointerType>())
872 .getPointer()};
873 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
874 };
875 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
876 UntiedCodeGen);
877 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000878 assert(!ThreadIDVar->getType()->isPointerType() &&
879 "thread id variable must be of type kmp_int32 for tasks");
880 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +0000881 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000882 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +0000883 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
884 InnermostKind,
885 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +0000886 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +0000887 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
888 if (!Tied)
889 NumberOfParts = Action.getNumberOfParts();
890 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000891}
892
Alexey Bataev50b3c952016-02-19 10:38:26 +0000893Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000894 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000895 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000896 if (!Entry) {
897 if (!DefaultOpenMPPSource) {
898 // Initialize default location for psource field of ident_t structure of
899 // all ident_t objects. Format is ";file;function;line;column;;".
900 // Taken from
901 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
902 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000903 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000904 DefaultOpenMPPSource =
905 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
906 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000907 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
908 CGM.getModule(), IdentTy, /*isConstant*/ true,
909 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000910 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000911 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000912
913 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000914 llvm::Constant *Values[] = {Zero,
915 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
916 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000917 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
918 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000919 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000920 }
John McCall7f416cc2015-09-08 08:05:57 +0000921 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000922}
923
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000924llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
925 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000926 unsigned Flags) {
927 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000928 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000929 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000930 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000931 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000932
933 assert(CGF.CurFn && "No function in current CodeGenFunction.");
934
John McCall7f416cc2015-09-08 08:05:57 +0000935 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000936 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
937 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000938 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
939
Alexander Musmanc6388682014-12-15 07:07:06 +0000940 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
941 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000942 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000943 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000944 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
945 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000946 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000947 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000948 LocValue = AI;
949
950 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
951 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000952 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000953 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000954 }
955
956 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000957 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000958
Alexey Bataevf002aca2014-05-30 05:48:40 +0000959 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
960 if (OMPDebugLoc == nullptr) {
961 SmallString<128> Buffer2;
962 llvm::raw_svector_ostream OS2(Buffer2);
963 // Build debug location
964 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
965 OS2 << ";" << PLoc.getFilename() << ";";
966 if (const FunctionDecl *FD =
967 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
968 OS2 << FD->getQualifiedNameAsString();
969 }
970 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
971 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
972 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000973 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000974 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000975 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
976
John McCall7f416cc2015-09-08 08:05:57 +0000977 // Our callers always pass this to a runtime function, so for
978 // convenience, go ahead and return a naked pointer.
979 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000980}
981
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000982llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
983 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000984 assert(CGF.CurFn && "No function in current CodeGenFunction.");
985
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000986 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000987 // Check whether we've already cached a load of the thread id in this
988 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000989 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000990 if (I != OpenMPLocThreadIDMap.end()) {
991 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000992 if (ThreadID != nullptr)
993 return ThreadID;
994 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000995 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000996 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000997 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000998 // Check if this an outlined function with thread id passed as argument.
999 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001000 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1001 // If value loaded in entry block, cache it and use it everywhere in
1002 // function.
1003 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1004 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1005 Elem.second.ThreadID = ThreadID;
1006 }
1007 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001008 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001009 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001010
1011 // This is not an outlined function region - need to call __kmpc_int32
1012 // kmpc_global_thread_num(ident_t *loc).
1013 // Generate thread id value and cache this value for use across the
1014 // function.
1015 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1016 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1017 ThreadID =
1018 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1019 emitUpdateLocation(CGF, Loc));
1020 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1021 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001022 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001023}
1024
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001025void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001026 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001027 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1028 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001029 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1030 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1031 UDRMap.erase(D);
1032 }
1033 FunctionUDRMap.erase(CGF.CurFn);
1034 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001035}
1036
1037llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001038 if (!IdentTy) {
1039 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001040 return llvm::PointerType::getUnqual(IdentTy);
1041}
1042
1043llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001044 if (!Kmpc_MicroTy) {
1045 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1046 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1047 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1048 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1049 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001050 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1051}
1052
1053llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001054CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001055 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001056 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001057 case OMPRTL__kmpc_fork_call: {
1058 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1059 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001060 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1061 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001062 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001063 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001064 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1065 break;
1066 }
1067 case OMPRTL__kmpc_global_thread_num: {
1068 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001069 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001070 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001071 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001072 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1073 break;
1074 }
Alexey Bataev97720002014-11-11 04:05:39 +00001075 case OMPRTL__kmpc_threadprivate_cached: {
1076 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1077 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1078 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1079 CGM.VoidPtrTy, CGM.SizeTy,
1080 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1081 llvm::FunctionType *FnTy =
1082 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1083 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1084 break;
1085 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001086 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001087 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1088 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001089 llvm::Type *TypeParams[] = {
1090 getIdentTyPointerTy(), CGM.Int32Ty,
1091 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1092 llvm::FunctionType *FnTy =
1093 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1094 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1095 break;
1096 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001097 case OMPRTL__kmpc_critical_with_hint: {
1098 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1099 // kmp_critical_name *crit, uintptr_t hint);
1100 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1101 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1102 CGM.IntPtrTy};
1103 llvm::FunctionType *FnTy =
1104 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1105 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1106 break;
1107 }
Alexey Bataev97720002014-11-11 04:05:39 +00001108 case OMPRTL__kmpc_threadprivate_register: {
1109 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1110 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1111 // typedef void *(*kmpc_ctor)(void *);
1112 auto KmpcCtorTy =
1113 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1114 /*isVarArg*/ false)->getPointerTo();
1115 // typedef void *(*kmpc_cctor)(void *, void *);
1116 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1117 auto KmpcCopyCtorTy =
1118 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1119 /*isVarArg*/ false)->getPointerTo();
1120 // typedef void (*kmpc_dtor)(void *);
1121 auto KmpcDtorTy =
1122 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1123 ->getPointerTo();
1124 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1125 KmpcCopyCtorTy, KmpcDtorTy};
1126 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1127 /*isVarArg*/ false);
1128 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1129 break;
1130 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001131 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001132 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1133 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001134 llvm::Type *TypeParams[] = {
1135 getIdentTyPointerTy(), CGM.Int32Ty,
1136 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1137 llvm::FunctionType *FnTy =
1138 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1139 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1140 break;
1141 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001142 case OMPRTL__kmpc_cancel_barrier: {
1143 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1144 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001145 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1146 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001147 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1148 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001149 break;
1150 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001151 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001152 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001153 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1154 llvm::FunctionType *FnTy =
1155 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1156 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1157 break;
1158 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001159 case OMPRTL__kmpc_for_static_fini: {
1160 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 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_for_static_fini");
1165 break;
1166 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001167 case OMPRTL__kmpc_push_num_threads: {
1168 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1169 // kmp_int32 num_threads)
1170 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1171 CGM.Int32Ty};
1172 llvm::FunctionType *FnTy =
1173 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1174 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1175 break;
1176 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001177 case OMPRTL__kmpc_serialized_parallel: {
1178 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1179 // global_tid);
1180 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1181 llvm::FunctionType *FnTy =
1182 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1183 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1184 break;
1185 }
1186 case OMPRTL__kmpc_end_serialized_parallel: {
1187 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1188 // global_tid);
1189 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1190 llvm::FunctionType *FnTy =
1191 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1192 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1193 break;
1194 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001195 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001196 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001197 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1198 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001199 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001200 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1201 break;
1202 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001203 case OMPRTL__kmpc_master: {
1204 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1205 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1206 llvm::FunctionType *FnTy =
1207 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1208 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1209 break;
1210 }
1211 case OMPRTL__kmpc_end_master: {
1212 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1213 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1214 llvm::FunctionType *FnTy =
1215 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1216 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1217 break;
1218 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001219 case OMPRTL__kmpc_omp_taskyield: {
1220 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1221 // int end_part);
1222 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1223 llvm::FunctionType *FnTy =
1224 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1225 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1226 break;
1227 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001228 case OMPRTL__kmpc_single: {
1229 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1230 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1231 llvm::FunctionType *FnTy =
1232 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1233 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1234 break;
1235 }
1236 case OMPRTL__kmpc_end_single: {
1237 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1238 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1239 llvm::FunctionType *FnTy =
1240 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1241 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1242 break;
1243 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001244 case OMPRTL__kmpc_omp_task_alloc: {
1245 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1246 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1247 // kmp_routine_entry_t *task_entry);
1248 assert(KmpRoutineEntryPtrTy != nullptr &&
1249 "Type kmp_routine_entry_t must be created.");
1250 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1251 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1252 // Return void * and then cast to particular kmp_task_t type.
1253 llvm::FunctionType *FnTy =
1254 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1255 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1256 break;
1257 }
1258 case OMPRTL__kmpc_omp_task: {
1259 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1260 // *new_task);
1261 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1262 CGM.VoidPtrTy};
1263 llvm::FunctionType *FnTy =
1264 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1265 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1266 break;
1267 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001268 case OMPRTL__kmpc_copyprivate: {
1269 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001270 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001271 // kmp_int32 didit);
1272 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1273 auto *CpyFnTy =
1274 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001275 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001276 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1277 CGM.Int32Ty};
1278 llvm::FunctionType *FnTy =
1279 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1280 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1281 break;
1282 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001283 case OMPRTL__kmpc_reduce: {
1284 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1285 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1286 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1287 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1288 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1289 /*isVarArg=*/false);
1290 llvm::Type *TypeParams[] = {
1291 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1292 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1293 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1294 llvm::FunctionType *FnTy =
1295 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1296 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1297 break;
1298 }
1299 case OMPRTL__kmpc_reduce_nowait: {
1300 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1301 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1302 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1303 // *lck);
1304 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1305 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1306 /*isVarArg=*/false);
1307 llvm::Type *TypeParams[] = {
1308 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1309 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1310 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1311 llvm::FunctionType *FnTy =
1312 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1313 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1314 break;
1315 }
1316 case OMPRTL__kmpc_end_reduce: {
1317 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1318 // kmp_critical_name *lck);
1319 llvm::Type *TypeParams[] = {
1320 getIdentTyPointerTy(), CGM.Int32Ty,
1321 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1322 llvm::FunctionType *FnTy =
1323 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1324 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1325 break;
1326 }
1327 case OMPRTL__kmpc_end_reduce_nowait: {
1328 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1329 // kmp_critical_name *lck);
1330 llvm::Type *TypeParams[] = {
1331 getIdentTyPointerTy(), CGM.Int32Ty,
1332 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1333 llvm::FunctionType *FnTy =
1334 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1335 RTLFn =
1336 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1337 break;
1338 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001339 case OMPRTL__kmpc_omp_task_begin_if0: {
1340 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1341 // *new_task);
1342 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1343 CGM.VoidPtrTy};
1344 llvm::FunctionType *FnTy =
1345 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1346 RTLFn =
1347 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1348 break;
1349 }
1350 case OMPRTL__kmpc_omp_task_complete_if0: {
1351 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1352 // *new_task);
1353 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1354 CGM.VoidPtrTy};
1355 llvm::FunctionType *FnTy =
1356 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1357 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1358 /*Name=*/"__kmpc_omp_task_complete_if0");
1359 break;
1360 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001361 case OMPRTL__kmpc_ordered: {
1362 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1363 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1364 llvm::FunctionType *FnTy =
1365 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1366 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1367 break;
1368 }
1369 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001370 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001371 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1372 llvm::FunctionType *FnTy =
1373 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1374 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1375 break;
1376 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001377 case OMPRTL__kmpc_omp_taskwait: {
1378 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1379 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1380 llvm::FunctionType *FnTy =
1381 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1382 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1383 break;
1384 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001385 case OMPRTL__kmpc_taskgroup: {
1386 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1387 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1388 llvm::FunctionType *FnTy =
1389 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1390 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1391 break;
1392 }
1393 case OMPRTL__kmpc_end_taskgroup: {
1394 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1395 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1396 llvm::FunctionType *FnTy =
1397 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1398 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1399 break;
1400 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001401 case OMPRTL__kmpc_push_proc_bind: {
1402 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1403 // int proc_bind)
1404 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1405 llvm::FunctionType *FnTy =
1406 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1407 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1408 break;
1409 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001410 case OMPRTL__kmpc_omp_task_with_deps: {
1411 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1412 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1413 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1414 llvm::Type *TypeParams[] = {
1415 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1416 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1417 llvm::FunctionType *FnTy =
1418 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1419 RTLFn =
1420 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1421 break;
1422 }
1423 case OMPRTL__kmpc_omp_wait_deps: {
1424 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1425 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1426 // kmp_depend_info_t *noalias_dep_list);
1427 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1428 CGM.Int32Ty, CGM.VoidPtrTy,
1429 CGM.Int32Ty, CGM.VoidPtrTy};
1430 llvm::FunctionType *FnTy =
1431 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1432 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1433 break;
1434 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001435 case OMPRTL__kmpc_cancellationpoint: {
1436 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1437 // global_tid, kmp_int32 cncl_kind)
1438 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1439 llvm::FunctionType *FnTy =
1440 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1441 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1442 break;
1443 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001444 case OMPRTL__kmpc_cancel: {
1445 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1446 // kmp_int32 cncl_kind)
1447 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1448 llvm::FunctionType *FnTy =
1449 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1450 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1451 break;
1452 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001453 case OMPRTL__kmpc_push_num_teams: {
1454 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1455 // kmp_int32 num_teams, kmp_int32 num_threads)
1456 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1457 CGM.Int32Ty};
1458 llvm::FunctionType *FnTy =
1459 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1460 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1461 break;
1462 }
1463 case OMPRTL__kmpc_fork_teams: {
1464 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1465 // microtask, ...);
1466 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1467 getKmpc_MicroPointerTy()};
1468 llvm::FunctionType *FnTy =
1469 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1470 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1471 break;
1472 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001473 case OMPRTL__kmpc_taskloop: {
1474 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1475 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1476 // sched, kmp_uint64 grainsize, void *task_dup);
1477 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1478 CGM.IntTy,
1479 CGM.VoidPtrTy,
1480 CGM.IntTy,
1481 CGM.Int64Ty->getPointerTo(),
1482 CGM.Int64Ty->getPointerTo(),
1483 CGM.Int64Ty,
1484 CGM.IntTy,
1485 CGM.IntTy,
1486 CGM.Int64Ty,
1487 CGM.VoidPtrTy};
1488 llvm::FunctionType *FnTy =
1489 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1490 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1491 break;
1492 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001493 case OMPRTL__kmpc_doacross_init: {
1494 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1495 // num_dims, struct kmp_dim *dims);
1496 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1497 CGM.Int32Ty,
1498 CGM.Int32Ty,
1499 CGM.VoidPtrTy};
1500 llvm::FunctionType *FnTy =
1501 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1502 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1503 break;
1504 }
1505 case OMPRTL__kmpc_doacross_fini: {
1506 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1507 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1508 llvm::FunctionType *FnTy =
1509 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1510 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1511 break;
1512 }
1513 case OMPRTL__kmpc_doacross_post: {
1514 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1515 // *vec);
1516 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1517 CGM.Int64Ty->getPointerTo()};
1518 llvm::FunctionType *FnTy =
1519 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1520 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1521 break;
1522 }
1523 case OMPRTL__kmpc_doacross_wait: {
1524 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1525 // *vec);
1526 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1527 CGM.Int64Ty->getPointerTo()};
1528 llvm::FunctionType *FnTy =
1529 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1530 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1531 break;
1532 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001533 case OMPRTL__tgt_target: {
1534 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1535 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1536 // *arg_types);
1537 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1538 CGM.VoidPtrTy,
1539 CGM.Int32Ty,
1540 CGM.VoidPtrPtrTy,
1541 CGM.VoidPtrPtrTy,
1542 CGM.SizeTy->getPointerTo(),
1543 CGM.Int32Ty->getPointerTo()};
1544 llvm::FunctionType *FnTy =
1545 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1546 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1547 break;
1548 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001549 case OMPRTL__tgt_target_teams: {
1550 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1551 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1552 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1553 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1554 CGM.VoidPtrTy,
1555 CGM.Int32Ty,
1556 CGM.VoidPtrPtrTy,
1557 CGM.VoidPtrPtrTy,
1558 CGM.SizeTy->getPointerTo(),
1559 CGM.Int32Ty->getPointerTo(),
1560 CGM.Int32Ty,
1561 CGM.Int32Ty};
1562 llvm::FunctionType *FnTy =
1563 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1564 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1565 break;
1566 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001567 case OMPRTL__tgt_register_lib: {
1568 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1569 QualType ParamTy =
1570 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1571 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1572 llvm::FunctionType *FnTy =
1573 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1574 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1575 break;
1576 }
1577 case OMPRTL__tgt_unregister_lib: {
1578 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1579 QualType ParamTy =
1580 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1581 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1582 llvm::FunctionType *FnTy =
1583 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1584 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1585 break;
1586 }
Samuel Antaodf158d52016-04-27 22:58:19 +00001587 case OMPRTL__tgt_target_data_begin: {
1588 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1589 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1590 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1591 CGM.Int32Ty,
1592 CGM.VoidPtrPtrTy,
1593 CGM.VoidPtrPtrTy,
1594 CGM.SizeTy->getPointerTo(),
1595 CGM.Int32Ty->getPointerTo()};
1596 llvm::FunctionType *FnTy =
1597 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1599 break;
1600 }
1601 case OMPRTL__tgt_target_data_end: {
1602 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1603 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1604 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1605 CGM.Int32Ty,
1606 CGM.VoidPtrPtrTy,
1607 CGM.VoidPtrPtrTy,
1608 CGM.SizeTy->getPointerTo(),
1609 CGM.Int32Ty->getPointerTo()};
1610 llvm::FunctionType *FnTy =
1611 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1612 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1613 break;
1614 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00001615 case OMPRTL__tgt_target_data_update: {
1616 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1617 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1618 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1619 CGM.Int32Ty,
1620 CGM.VoidPtrPtrTy,
1621 CGM.VoidPtrPtrTy,
1622 CGM.SizeTy->getPointerTo(),
1623 CGM.Int32Ty->getPointerTo()};
1624 llvm::FunctionType *FnTy =
1625 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1626 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1627 break;
1628 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001629 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001630 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001631 return RTLFn;
1632}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001633
Alexander Musman21212e42015-03-13 10:38:23 +00001634llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1635 bool IVSigned) {
1636 assert((IVSize == 32 || IVSize == 64) &&
1637 "IV size is not compatible with the omp runtime");
1638 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1639 : "__kmpc_for_static_init_4u")
1640 : (IVSigned ? "__kmpc_for_static_init_8"
1641 : "__kmpc_for_static_init_8u");
1642 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1643 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1644 llvm::Type *TypeParams[] = {
1645 getIdentTyPointerTy(), // loc
1646 CGM.Int32Ty, // tid
1647 CGM.Int32Ty, // schedtype
1648 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1649 PtrTy, // p_lower
1650 PtrTy, // p_upper
1651 PtrTy, // p_stride
1652 ITy, // incr
1653 ITy // chunk
1654 };
1655 llvm::FunctionType *FnTy =
1656 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1657 return CGM.CreateRuntimeFunction(FnTy, Name);
1658}
1659
Alexander Musman92bdaab2015-03-12 13:37:50 +00001660llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1661 bool IVSigned) {
1662 assert((IVSize == 32 || IVSize == 64) &&
1663 "IV size is not compatible with the omp runtime");
1664 auto Name =
1665 IVSize == 32
1666 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1667 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1668 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1669 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1670 CGM.Int32Ty, // tid
1671 CGM.Int32Ty, // schedtype
1672 ITy, // lower
1673 ITy, // upper
1674 ITy, // stride
1675 ITy // chunk
1676 };
1677 llvm::FunctionType *FnTy =
1678 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1679 return CGM.CreateRuntimeFunction(FnTy, Name);
1680}
1681
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001682llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1683 bool IVSigned) {
1684 assert((IVSize == 32 || IVSize == 64) &&
1685 "IV size is not compatible with the omp runtime");
1686 auto Name =
1687 IVSize == 32
1688 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1689 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1690 llvm::Type *TypeParams[] = {
1691 getIdentTyPointerTy(), // loc
1692 CGM.Int32Ty, // tid
1693 };
1694 llvm::FunctionType *FnTy =
1695 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1696 return CGM.CreateRuntimeFunction(FnTy, Name);
1697}
1698
Alexander Musman92bdaab2015-03-12 13:37:50 +00001699llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1700 bool IVSigned) {
1701 assert((IVSize == 32 || IVSize == 64) &&
1702 "IV size is not compatible with the omp runtime");
1703 auto Name =
1704 IVSize == 32
1705 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1706 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1707 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1708 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1709 llvm::Type *TypeParams[] = {
1710 getIdentTyPointerTy(), // loc
1711 CGM.Int32Ty, // tid
1712 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1713 PtrTy, // p_lower
1714 PtrTy, // p_upper
1715 PtrTy // p_stride
1716 };
1717 llvm::FunctionType *FnTy =
1718 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1719 return CGM.CreateRuntimeFunction(FnTy, Name);
1720}
1721
Alexey Bataev97720002014-11-11 04:05:39 +00001722llvm::Constant *
1723CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001724 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1725 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001726 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001727 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001728 Twine(CGM.getMangledName(VD)) + ".cache.");
1729}
1730
John McCall7f416cc2015-09-08 08:05:57 +00001731Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1732 const VarDecl *VD,
1733 Address VDAddr,
1734 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001735 if (CGM.getLangOpts().OpenMPUseTLS &&
1736 CGM.getContext().getTargetInfo().isTLSSupported())
1737 return VDAddr;
1738
John McCall7f416cc2015-09-08 08:05:57 +00001739 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001740 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001741 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1742 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001743 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1744 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001745 return Address(CGF.EmitRuntimeCall(
1746 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1747 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001748}
1749
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001750void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001751 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001752 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1753 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1754 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001755 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1756 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001757 OMPLoc);
1758 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1759 // to register constructor/destructor for variable.
1760 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001761 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1762 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001763 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001764 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001765 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001766}
1767
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001768llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001769 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001770 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001771 if (CGM.getLangOpts().OpenMPUseTLS &&
1772 CGM.getContext().getTargetInfo().isTLSSupported())
1773 return nullptr;
1774
Alexey Bataev97720002014-11-11 04:05:39 +00001775 VD = VD->getDefinition(CGM.getContext());
1776 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1777 ThreadPrivateWithDefinition.insert(VD);
1778 QualType ASTTy = VD->getType();
1779
1780 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1781 auto Init = VD->getAnyInitializer();
1782 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1783 // Generate function that re-emits the declaration's initializer into the
1784 // threadprivate copy of the variable VD
1785 CodeGenFunction CtorCGF(CGM);
1786 FunctionArgList Args;
1787 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1788 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1789 Args.push_back(&Dst);
1790
John McCallc56a8b32016-03-11 04:30:31 +00001791 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1792 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001793 auto FTy = CGM.getTypes().GetFunctionType(FI);
1794 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001795 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001796 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1797 Args, SourceLocation());
1798 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001799 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001800 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001801 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1802 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1803 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001804 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1805 /*IsInitializer=*/true);
1806 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001807 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001808 CGM.getContext().VoidPtrTy, Dst.getLocation());
1809 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1810 CtorCGF.FinishFunction();
1811 Ctor = Fn;
1812 }
1813 if (VD->getType().isDestructedType() != QualType::DK_none) {
1814 // Generate function that emits destructor call for the threadprivate copy
1815 // of the variable VD
1816 CodeGenFunction DtorCGF(CGM);
1817 FunctionArgList Args;
1818 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1819 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1820 Args.push_back(&Dst);
1821
John McCallc56a8b32016-03-11 04:30:31 +00001822 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1823 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001824 auto FTy = CGM.getTypes().GetFunctionType(FI);
1825 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001826 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00001827 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001828 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1829 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00001830 // Create a scope with an artificial location for the body of this function.
1831 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001832 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1833 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001834 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1835 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001836 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1837 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1838 DtorCGF.FinishFunction();
1839 Dtor = Fn;
1840 }
1841 // Do not emit init function if it is not required.
1842 if (!Ctor && !Dtor)
1843 return nullptr;
1844
1845 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1846 auto CopyCtorTy =
1847 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1848 /*isVarArg=*/false)->getPointerTo();
1849 // Copying constructor for the threadprivate variable.
1850 // Must be NULL - reserved by runtime, but currently it requires that this
1851 // parameter is always NULL. Otherwise it fires assertion.
1852 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1853 if (Ctor == nullptr) {
1854 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1855 /*isVarArg=*/false)->getPointerTo();
1856 Ctor = llvm::Constant::getNullValue(CtorTy);
1857 }
1858 if (Dtor == nullptr) {
1859 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1860 /*isVarArg=*/false)->getPointerTo();
1861 Dtor = llvm::Constant::getNullValue(DtorTy);
1862 }
1863 if (!CGF) {
1864 auto InitFunctionTy =
1865 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1866 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001867 InitFunctionTy, ".__omp_threadprivate_init_.",
1868 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001869 CodeGenFunction InitCGF(CGM);
1870 FunctionArgList ArgList;
1871 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1872 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1873 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001874 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001875 InitCGF.FinishFunction();
1876 return InitFunction;
1877 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001878 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001879 }
1880 return nullptr;
1881}
1882
Alexey Bataev1d677132015-04-22 13:57:31 +00001883/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1884/// function. Here is the logic:
1885/// if (Cond) {
1886/// ThenGen();
1887/// } else {
1888/// ElseGen();
1889/// }
1890static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1891 const RegionCodeGenTy &ThenGen,
1892 const RegionCodeGenTy &ElseGen) {
1893 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1894
1895 // If the condition constant folds and can be elided, try to avoid emitting
1896 // the condition and the dead arm of the if/else.
1897 bool CondConstant;
1898 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001899 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001900 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001901 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001902 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001903 return;
1904 }
1905
1906 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1907 // emit the conditional branch.
1908 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1909 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1910 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1911 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1912
1913 // Emit the 'then' code.
1914 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001915 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001916 CGF.EmitBranch(ContBlock);
1917 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001918 // There is no need to emit line number for unconditional branch.
1919 (void)ApplyDebugLocation::CreateEmpty(CGF);
1920 CGF.EmitBlock(ElseBlock);
1921 ElseGen(CGF);
1922 // There is no need to emit line number for unconditional branch.
1923 (void)ApplyDebugLocation::CreateEmpty(CGF);
1924 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001925 // Emit the continuation block for code after the if.
1926 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001927}
1928
Alexey Bataev1d677132015-04-22 13:57:31 +00001929void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1930 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001931 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001932 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001933 if (!CGF.HaveInsertPoint())
1934 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001935 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001936 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1937 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001938 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001939 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001940 llvm::Value *Args[] = {
1941 RTLoc,
1942 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001943 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001944 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1945 RealArgs.append(std::begin(Args), std::end(Args));
1946 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1947
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001948 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001949 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1950 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001951 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1952 PrePostActionTy &) {
1953 auto &RT = CGF.CGM.getOpenMPRuntime();
1954 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001955 // Build calls:
1956 // __kmpc_serialized_parallel(&Loc, GTid);
1957 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001958 CGF.EmitRuntimeCall(
1959 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001960
Alexey Bataev1d677132015-04-22 13:57:31 +00001961 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001962 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001963 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001964 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1965 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001966 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001967 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1968 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1969 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1970 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001971 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001972
Alexey Bataev1d677132015-04-22 13:57:31 +00001973 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001974 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001975 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001976 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
1977 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00001978 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001979 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00001980 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001981 else {
1982 RegionCodeGenTy ThenRCG(ThenGen);
1983 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00001984 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001985}
1986
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001987// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001988// thread-ID variable (it is passed in a first argument of the outlined function
1989// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1990// regular serial code region, get thread ID by calling kmp_int32
1991// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1992// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001993Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1994 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001995 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001996 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001997 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001998 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001999
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002000 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002001 auto Int32Ty =
2002 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2003 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2004 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002005 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002006
2007 return ThreadIDTemp;
2008}
2009
Alexey Bataev97720002014-11-11 04:05:39 +00002010llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002011CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002012 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002013 SmallString<256> Buffer;
2014 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002015 Out << Name;
2016 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002017 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2018 if (Elem.second) {
2019 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002020 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002021 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002022 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002023
David Blaikie13156b62014-11-19 03:06:06 +00002024 return Elem.second = new llvm::GlobalVariable(
2025 CGM.getModule(), Ty, /*IsConstant*/ false,
2026 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2027 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002028}
2029
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002030llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002031 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002032 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002033}
2034
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002035namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002036/// Common pre(post)-action for different OpenMP constructs.
2037class CommonActionTy final : public PrePostActionTy {
2038 llvm::Value *EnterCallee;
2039 ArrayRef<llvm::Value *> EnterArgs;
2040 llvm::Value *ExitCallee;
2041 ArrayRef<llvm::Value *> ExitArgs;
2042 bool Conditional;
2043 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002044
2045public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002046 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2047 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2048 bool Conditional = false)
2049 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2050 ExitArgs(ExitArgs), Conditional(Conditional) {}
2051 void Enter(CodeGenFunction &CGF) override {
2052 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2053 if (Conditional) {
2054 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2055 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2056 ContBlock = CGF.createBasicBlock("omp_if.end");
2057 // Generate the branch (If-stmt)
2058 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2059 CGF.EmitBlock(ThenBlock);
2060 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002061 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002062 void Done(CodeGenFunction &CGF) {
2063 // Emit the rest of blocks/branches
2064 CGF.EmitBranch(ContBlock);
2065 CGF.EmitBlock(ContBlock, true);
2066 }
2067 void Exit(CodeGenFunction &CGF) override {
2068 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002069 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002070};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002071} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002072
2073void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2074 StringRef CriticalName,
2075 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002076 SourceLocation Loc, const Expr *Hint) {
2077 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002078 // CriticalOpGen();
2079 // __kmpc_end_critical(ident_t *, gtid, Lock);
2080 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002081 if (!CGF.HaveInsertPoint())
2082 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002083 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2084 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002085 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2086 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002087 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002088 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2089 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2090 }
2091 CommonActionTy Action(
2092 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2093 : OMPRTL__kmpc_critical),
2094 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2095 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002096 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002097}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002098
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002099void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002100 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002101 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002102 if (!CGF.HaveInsertPoint())
2103 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002104 // if(__kmpc_master(ident_t *, gtid)) {
2105 // MasterOpGen();
2106 // __kmpc_end_master(ident_t *, gtid);
2107 // }
2108 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002109 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002110 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2111 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2112 /*Conditional=*/true);
2113 MasterOpGen.setAction(Action);
2114 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2115 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002116}
2117
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002118void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2119 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002120 if (!CGF.HaveInsertPoint())
2121 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002122 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2123 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002124 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002125 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002126 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002127 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2128 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002129}
2130
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002131void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2132 const RegionCodeGenTy &TaskgroupOpGen,
2133 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002134 if (!CGF.HaveInsertPoint())
2135 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002136 // __kmpc_taskgroup(ident_t *, gtid);
2137 // TaskgroupOpGen();
2138 // __kmpc_end_taskgroup(ident_t *, gtid);
2139 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002140 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2141 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2142 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2143 Args);
2144 TaskgroupOpGen.setAction(Action);
2145 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002146}
2147
John McCall7f416cc2015-09-08 08:05:57 +00002148/// Given an array of pointers to variables, project the address of a
2149/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002150static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2151 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002152 // Pull out the pointer to the variable.
2153 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002154 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002155 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2156
2157 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002158 Addr = CGF.Builder.CreateElementBitCast(
2159 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002160 return Addr;
2161}
2162
Alexey Bataeva63048e2015-03-23 06:18:07 +00002163static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002164 CodeGenModule &CGM, llvm::Type *ArgsType,
2165 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2166 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002167 auto &C = CGM.getContext();
2168 // void copy_func(void *LHSArg, void *RHSArg);
2169 FunctionArgList Args;
2170 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2171 C.VoidPtrTy);
2172 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2173 C.VoidPtrTy);
2174 Args.push_back(&LHSArg);
2175 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002176 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002177 auto *Fn = llvm::Function::Create(
2178 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2179 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002180 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002181 CodeGenFunction CGF(CGM);
2182 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002183 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002184 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002185 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2186 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2187 ArgsType), CGF.getPointerAlign());
2188 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2189 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2190 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002191 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2192 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2193 // ...
2194 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002195 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002196 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2197 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2198
2199 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2200 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2201
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002202 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2203 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002204 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002205 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002206 CGF.FinishFunction();
2207 return Fn;
2208}
2209
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002210void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002211 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002212 SourceLocation Loc,
2213 ArrayRef<const Expr *> CopyprivateVars,
2214 ArrayRef<const Expr *> SrcExprs,
2215 ArrayRef<const Expr *> DstExprs,
2216 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002217 if (!CGF.HaveInsertPoint())
2218 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002219 assert(CopyprivateVars.size() == SrcExprs.size() &&
2220 CopyprivateVars.size() == DstExprs.size() &&
2221 CopyprivateVars.size() == AssignmentOps.size());
2222 auto &C = CGM.getContext();
2223 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002224 // if(__kmpc_single(ident_t *, gtid)) {
2225 // SingleOpGen();
2226 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002227 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002228 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002229 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2230 // <copy_func>, did_it);
2231
John McCall7f416cc2015-09-08 08:05:57 +00002232 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002233 if (!CopyprivateVars.empty()) {
2234 // int32 did_it = 0;
2235 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2236 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002237 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002238 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002239 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002240 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002241 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2242 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2243 /*Conditional=*/true);
2244 SingleOpGen.setAction(Action);
2245 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2246 if (DidIt.isValid()) {
2247 // did_it = 1;
2248 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2249 }
2250 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002251 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2252 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002253 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002254 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2255 auto CopyprivateArrayTy =
2256 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2257 /*IndexTypeQuals=*/0);
2258 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002259 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002260 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2261 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002262 Address Elem = CGF.Builder.CreateConstArrayGEP(
2263 CopyprivateList, I, CGF.getPointerSize());
2264 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002265 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002266 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2267 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002268 }
2269 // Build function that copies private values from single region to all other
2270 // threads in the corresponding parallel region.
2271 auto *CpyFn = emitCopyprivateCopyFunction(
2272 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002273 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002274 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002275 Address CL =
2276 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2277 CGF.VoidPtrTy);
2278 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002279 llvm::Value *Args[] = {
2280 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2281 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002282 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002283 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002284 CpyFn, // void (*) (void *, void *) <copy_func>
2285 DidItVal // i32 did_it
2286 };
2287 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2288 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002289}
2290
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002291void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2292 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002293 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002294 if (!CGF.HaveInsertPoint())
2295 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002296 // __kmpc_ordered(ident_t *, gtid);
2297 // OrderedOpGen();
2298 // __kmpc_end_ordered(ident_t *, gtid);
2299 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002300 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002301 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002302 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2303 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2304 Args);
2305 OrderedOpGen.setAction(Action);
2306 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2307 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002308 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002309 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002310}
2311
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002312void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002313 OpenMPDirectiveKind Kind, bool EmitChecks,
2314 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002315 if (!CGF.HaveInsertPoint())
2316 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002317 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002318 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002319 unsigned Flags;
2320 if (Kind == OMPD_for)
2321 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2322 else if (Kind == OMPD_sections)
2323 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2324 else if (Kind == OMPD_single)
2325 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2326 else if (Kind == OMPD_barrier)
2327 Flags = OMP_IDENT_BARRIER_EXPL;
2328 else
2329 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002330 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2331 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002332 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2333 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002334 if (auto *OMPRegionInfo =
2335 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002336 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002337 auto *Result = CGF.EmitRuntimeCall(
2338 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002339 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002340 // if (__kmpc_cancel_barrier()) {
2341 // exit from construct;
2342 // }
2343 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2344 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2345 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2346 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2347 CGF.EmitBlock(ExitBB);
2348 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002349 auto CancelDestination =
2350 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002351 CGF.EmitBranchThroughCleanup(CancelDestination);
2352 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2353 }
2354 return;
2355 }
2356 }
2357 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002358}
2359
Alexander Musmanc6388682014-12-15 07:07:06 +00002360/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2361static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002362 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002363 switch (ScheduleKind) {
2364 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002365 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2366 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002367 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002368 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002369 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002370 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002371 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002372 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2373 case OMPC_SCHEDULE_auto:
2374 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002375 case OMPC_SCHEDULE_unknown:
2376 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002377 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002378 }
2379 llvm_unreachable("Unexpected runtime schedule");
2380}
2381
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002382/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2383static OpenMPSchedType
2384getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2385 // only static is allowed for dist_schedule
2386 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2387}
2388
Alexander Musmanc6388682014-12-15 07:07:06 +00002389bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2390 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002391 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002392 return Schedule == OMP_sch_static;
2393}
2394
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002395bool CGOpenMPRuntime::isStaticNonchunked(
2396 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2397 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2398 return Schedule == OMP_dist_sch_static;
2399}
2400
2401
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002402bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002403 auto Schedule =
2404 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002405 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2406 return Schedule != OMP_sch_static;
2407}
2408
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002409static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2410 OpenMPScheduleClauseModifier M1,
2411 OpenMPScheduleClauseModifier M2) {
2412 switch (M1) {
2413 case OMPC_SCHEDULE_MODIFIER_monotonic:
2414 return Schedule | OMP_sch_modifier_monotonic;
2415 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2416 return Schedule | OMP_sch_modifier_nonmonotonic;
2417 case OMPC_SCHEDULE_MODIFIER_simd:
2418 case OMPC_SCHEDULE_MODIFIER_last:
2419 case OMPC_SCHEDULE_MODIFIER_unknown:
2420 break;
2421 }
2422 switch (M2) {
2423 case OMPC_SCHEDULE_MODIFIER_monotonic:
2424 return Schedule | OMP_sch_modifier_monotonic;
2425 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2426 return Schedule | OMP_sch_modifier_nonmonotonic;
2427 case OMPC_SCHEDULE_MODIFIER_simd:
2428 case OMPC_SCHEDULE_MODIFIER_last:
2429 case OMPC_SCHEDULE_MODIFIER_unknown:
2430 break;
2431 }
2432 return Schedule;
2433}
2434
John McCall7f416cc2015-09-08 08:05:57 +00002435void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2436 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002437 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002438 unsigned IVSize, bool IVSigned,
2439 bool Ordered, llvm::Value *UB,
2440 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002441 if (!CGF.HaveInsertPoint())
2442 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002443 OpenMPSchedType Schedule =
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002444 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002445 assert(Ordered ||
2446 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2447 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
2448 // Call __kmpc_dispatch_init(
2449 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2450 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2451 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002452
John McCall7f416cc2015-09-08 08:05:57 +00002453 // If the Chunk was not specified in the clause - use default value 1.
2454 if (Chunk == nullptr)
2455 Chunk = CGF.Builder.getIntN(IVSize, 1);
2456 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002457 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2458 CGF.Builder.getInt32(addMonoNonMonoModifier(
2459 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2460 CGF.Builder.getIntN(IVSize, 0), // Lower
2461 UB, // Upper
2462 CGF.Builder.getIntN(IVSize, 1), // Stride
2463 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002464 };
2465 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2466}
2467
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002468static void emitForStaticInitCall(
2469 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2470 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2471 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2472 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2473 Address ST, llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002474 if (!CGF.HaveInsertPoint())
2475 return;
2476
2477 assert(!Ordered);
2478 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2479 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2480 Schedule == OMP_dist_sch_static ||
2481 Schedule == OMP_dist_sch_static_chunked);
2482
2483 // Call __kmpc_for_static_init(
2484 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2485 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2486 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2487 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2488 if (Chunk == nullptr) {
2489 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2490 Schedule == OMP_dist_sch_static) &&
2491 "expected static non-chunked schedule");
2492 // If the Chunk was not specified in the clause - use default value 1.
2493 Chunk = CGF.Builder.getIntN(IVSize, 1);
2494 } else {
2495 assert((Schedule == OMP_sch_static_chunked ||
2496 Schedule == OMP_ord_static_chunked ||
2497 Schedule == OMP_dist_sch_static_chunked) &&
2498 "expected static chunked schedule");
2499 }
2500 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002501 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2502 Schedule, M1, M2)), // Schedule type
2503 IL.getPointer(), // &isLastIter
2504 LB.getPointer(), // &LB
2505 UB.getPointer(), // &UB
2506 ST.getPointer(), // &Stride
2507 CGF.Builder.getIntN(IVSize, 1), // Incr
2508 Chunk // Chunk
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002509 };
2510 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2511}
2512
John McCall7f416cc2015-09-08 08:05:57 +00002513void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2514 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002515 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002516 unsigned IVSize, bool IVSigned,
2517 bool Ordered, Address IL, Address LB,
2518 Address UB, Address ST,
2519 llvm::Value *Chunk) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002520 OpenMPSchedType ScheduleNum =
2521 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002522 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2523 auto *ThreadId = getThreadID(CGF, Loc);
2524 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002525 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2526 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2527 Ordered, IL, LB, UB, ST, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002528}
John McCall7f416cc2015-09-08 08:05:57 +00002529
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002530void CGOpenMPRuntime::emitDistributeStaticInit(
2531 CodeGenFunction &CGF, SourceLocation Loc,
2532 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2533 bool Ordered, Address IL, Address LB, Address UB, Address ST,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002534 llvm::Value *Chunk) {
2535 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2536 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2537 auto *ThreadId = getThreadID(CGF, Loc);
2538 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002539 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2540 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2541 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2542 UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002543}
2544
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002545void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2546 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002547 if (!CGF.HaveInsertPoint())
2548 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002549 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002550 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002551 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2552 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002553}
2554
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002555void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2556 SourceLocation Loc,
2557 unsigned IVSize,
2558 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002559 if (!CGF.HaveInsertPoint())
2560 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002561 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002562 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002563 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2564}
2565
Alexander Musman92bdaab2015-03-12 13:37:50 +00002566llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2567 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002568 bool IVSigned, Address IL,
2569 Address LB, Address UB,
2570 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002571 // Call __kmpc_dispatch_next(
2572 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2573 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2574 // kmp_int[32|64] *p_stride);
2575 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002576 emitUpdateLocation(CGF, Loc),
2577 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002578 IL.getPointer(), // &isLastIter
2579 LB.getPointer(), // &Lower
2580 UB.getPointer(), // &Upper
2581 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002582 };
2583 llvm::Value *Call =
2584 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2585 return CGF.EmitScalarConversion(
2586 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002587 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002588}
2589
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002590void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2591 llvm::Value *NumThreads,
2592 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002593 if (!CGF.HaveInsertPoint())
2594 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002595 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2596 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002597 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002598 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002599 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2600 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002601}
2602
Alexey Bataev7f210c62015-06-18 13:40:03 +00002603void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2604 OpenMPProcBindClauseKind ProcBind,
2605 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002606 if (!CGF.HaveInsertPoint())
2607 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002608 // Constants for proc bind value accepted by the runtime.
2609 enum ProcBindTy {
2610 ProcBindFalse = 0,
2611 ProcBindTrue,
2612 ProcBindMaster,
2613 ProcBindClose,
2614 ProcBindSpread,
2615 ProcBindIntel,
2616 ProcBindDefault
2617 } RuntimeProcBind;
2618 switch (ProcBind) {
2619 case OMPC_PROC_BIND_master:
2620 RuntimeProcBind = ProcBindMaster;
2621 break;
2622 case OMPC_PROC_BIND_close:
2623 RuntimeProcBind = ProcBindClose;
2624 break;
2625 case OMPC_PROC_BIND_spread:
2626 RuntimeProcBind = ProcBindSpread;
2627 break;
2628 case OMPC_PROC_BIND_unknown:
2629 llvm_unreachable("Unsupported proc_bind value.");
2630 }
2631 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2632 llvm::Value *Args[] = {
2633 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2634 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2635 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2636}
2637
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002638void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2639 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002640 if (!CGF.HaveInsertPoint())
2641 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002642 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002643 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2644 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002645}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002646
Alexey Bataev62b63b12015-03-10 07:28:44 +00002647namespace {
2648/// \brief Indexes of fields for type kmp_task_t.
2649enum KmpTaskTFields {
2650 /// \brief List of shared variables.
2651 KmpTaskTShareds,
2652 /// \brief Task routine.
2653 KmpTaskTRoutine,
2654 /// \brief Partition id for the untied tasks.
2655 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00002656 /// Function with call of destructors for private variables.
2657 Data1,
2658 /// Task priority.
2659 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00002660 /// (Taskloops only) Lower bound.
2661 KmpTaskTLowerBound,
2662 /// (Taskloops only) Upper bound.
2663 KmpTaskTUpperBound,
2664 /// (Taskloops only) Stride.
2665 KmpTaskTStride,
2666 /// (Taskloops only) Is last iteration flag.
2667 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00002668};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002669} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002670
Samuel Antaoee8fb302016-01-06 13:42:12 +00002671bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2672 // FIXME: Add other entries type when they become supported.
2673 return OffloadEntriesTargetRegion.empty();
2674}
2675
2676/// \brief Initialize target region entry.
2677void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2678 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2679 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002680 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002681 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2682 "only required for the device "
2683 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002684 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002685 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2686 ++OffloadingEntriesNum;
2687}
2688
2689void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2690 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2691 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002692 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002693 // If we are emitting code for a target, the entry is already initialized,
2694 // only has to be registered.
2695 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002696 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002697 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002698 auto &Entry =
2699 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002700 assert(Entry.isValid() && "Entry not initialized!");
2701 Entry.setAddress(Addr);
2702 Entry.setID(ID);
2703 return;
2704 } else {
2705 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002706 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002707 }
2708}
2709
2710bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002711 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2712 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002713 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2714 if (PerDevice == OffloadEntriesTargetRegion.end())
2715 return false;
2716 auto PerFile = PerDevice->second.find(FileID);
2717 if (PerFile == PerDevice->second.end())
2718 return false;
2719 auto PerParentName = PerFile->second.find(ParentName);
2720 if (PerParentName == PerFile->second.end())
2721 return false;
2722 auto PerLine = PerParentName->second.find(LineNum);
2723 if (PerLine == PerParentName->second.end())
2724 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002725 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002726 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002727 return false;
2728 return true;
2729}
2730
2731void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2732 const OffloadTargetRegionEntryInfoActTy &Action) {
2733 // Scan all target region entries and perform the provided action.
2734 for (auto &D : OffloadEntriesTargetRegion)
2735 for (auto &F : D.second)
2736 for (auto &P : F.second)
2737 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002738 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002739}
2740
2741/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2742/// \a Codegen. This is used to emit the two functions that register and
2743/// unregister the descriptor of the current compilation unit.
2744static llvm::Function *
2745createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2746 const RegionCodeGenTy &Codegen) {
2747 auto &C = CGM.getContext();
2748 FunctionArgList Args;
2749 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2750 /*Id=*/nullptr, C.VoidPtrTy);
2751 Args.push_back(&DummyPtr);
2752
2753 CodeGenFunction CGF(CGM);
2754 GlobalDecl();
John McCallc56a8b32016-03-11 04:30:31 +00002755 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002756 auto FTy = CGM.getTypes().GetFunctionType(FI);
2757 auto *Fn =
2758 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2759 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2760 Codegen(CGF);
2761 CGF.FinishFunction();
2762 return Fn;
2763}
2764
2765llvm::Function *
2766CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2767
2768 // If we don't have entries or if we are emitting code for the device, we
2769 // don't need to do anything.
2770 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2771 return nullptr;
2772
2773 auto &M = CGM.getModule();
2774 auto &C = CGM.getContext();
2775
2776 // Get list of devices we care about
2777 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2778
2779 // We should be creating an offloading descriptor only if there are devices
2780 // specified.
2781 assert(!Devices.empty() && "No OpenMP offloading devices??");
2782
2783 // Create the external variables that will point to the begin and end of the
2784 // host entries section. These will be defined by the linker.
2785 auto *OffloadEntryTy =
2786 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2787 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2788 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002789 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002790 ".omp_offloading.entries_begin");
2791 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2792 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002793 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002794 ".omp_offloading.entries_end");
2795
2796 // Create all device images
2797 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2798 auto *DeviceImageTy = cast<llvm::StructType>(
2799 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2800
2801 for (unsigned i = 0; i < Devices.size(); ++i) {
2802 StringRef T = Devices[i].getTriple();
2803 auto *ImgBegin = new llvm::GlobalVariable(
2804 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002805 /*Initializer=*/nullptr,
2806 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002807 auto *ImgEnd = new llvm::GlobalVariable(
2808 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002809 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002810
2811 llvm::Constant *Dev =
2812 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2813 HostEntriesBegin, HostEntriesEnd, nullptr);
2814 DeviceImagesEntires.push_back(Dev);
2815 }
2816
2817 // Create device images global array.
2818 llvm::ArrayType *DeviceImagesInitTy =
2819 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2820 llvm::Constant *DeviceImagesInit =
2821 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2822
2823 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2824 M, DeviceImagesInitTy, /*isConstant=*/true,
2825 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2826 ".omp_offloading.device_images");
2827 DeviceImages->setUnnamedAddr(true);
2828
2829 // This is a Zero array to be used in the creation of the constant expressions
2830 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2831 llvm::Constant::getNullValue(CGM.Int32Ty)};
2832
2833 // Create the target region descriptor.
2834 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2835 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2836 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2837 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2838 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2839 Index),
2840 HostEntriesBegin, HostEntriesEnd, nullptr);
2841
2842 auto *Desc = new llvm::GlobalVariable(
2843 M, BinaryDescriptorTy, /*isConstant=*/true,
2844 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2845 ".omp_offloading.descriptor");
2846
2847 // Emit code to register or unregister the descriptor at execution
2848 // startup or closing, respectively.
2849
2850 // Create a variable to drive the registration and unregistration of the
2851 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2852 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2853 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2854 IdentInfo, C.CharTy);
2855
2856 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002857 CGM, ".omp_offloading.descriptor_unreg",
2858 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002859 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2860 Desc);
2861 });
2862 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002863 CGM, ".omp_offloading.descriptor_reg",
2864 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002865 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2866 Desc);
2867 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2868 });
2869 return RegFn;
2870}
2871
Samuel Antao2de62b02016-02-13 23:35:10 +00002872void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2873 llvm::Constant *Addr, uint64_t Size) {
2874 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002875 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2876 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2877 llvm::LLVMContext &C = CGM.getModule().getContext();
2878 llvm::Module &M = CGM.getModule();
2879
2880 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002881 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002882
2883 // Create constant string with the name.
2884 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2885
2886 llvm::GlobalVariable *Str =
2887 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2888 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2889 ".omp_offloading.entry_name");
2890 Str->setUnnamedAddr(true);
2891 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2892
2893 // Create the entry struct.
2894 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2895 TgtOffloadEntryType, AddrPtr, StrPtr,
2896 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2897 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2898 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2899 EntryInit, ".omp_offloading.entry");
2900
2901 // The entry has to be created in the section the linker expects it to be.
2902 Entry->setSection(".omp_offloading.entries");
2903 // We can't have any padding between symbols, so we need to have 1-byte
2904 // alignment.
2905 Entry->setAlignment(1);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002906}
2907
2908void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2909 // Emit the offloading entries and metadata so that the device codegen side
2910 // can
2911 // easily figure out what to emit. The produced metadata looks like this:
2912 //
2913 // !omp_offload.info = !{!1, ...}
2914 //
2915 // Right now we only generate metadata for function that contain target
2916 // regions.
2917
2918 // If we do not have entries, we dont need to do anything.
2919 if (OffloadEntriesInfoManager.empty())
2920 return;
2921
2922 llvm::Module &M = CGM.getModule();
2923 llvm::LLVMContext &C = M.getContext();
2924 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2925 OrderedEntries(OffloadEntriesInfoManager.size());
2926
2927 // Create the offloading info metadata node.
2928 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2929
2930 // Auxiliar methods to create metadata values and strings.
2931 auto getMDInt = [&](unsigned v) {
2932 return llvm::ConstantAsMetadata::get(
2933 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2934 };
2935
2936 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2937
2938 // Create function that emits metadata for each target region entry;
2939 auto &&TargetRegionMetadataEmitter = [&](
2940 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002941 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2942 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2943 // Generate metadata for target regions. Each entry of this metadata
2944 // contains:
2945 // - Entry 0 -> Kind of this type of metadata (0).
2946 // - Entry 1 -> Device ID of the file where the entry was identified.
2947 // - Entry 2 -> File ID of the file where the entry was identified.
2948 // - Entry 3 -> Mangled name of the function where the entry was identified.
2949 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002950 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002951 // The first element of the metadata node is the kind.
2952 Ops.push_back(getMDInt(E.getKind()));
2953 Ops.push_back(getMDInt(DeviceID));
2954 Ops.push_back(getMDInt(FileID));
2955 Ops.push_back(getMDString(ParentName));
2956 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002957 Ops.push_back(getMDInt(E.getOrder()));
2958
2959 // Save this entry in the right position of the ordered entries array.
2960 OrderedEntries[E.getOrder()] = &E;
2961
2962 // Add metadata to the named metadata node.
2963 MD->addOperand(llvm::MDNode::get(C, Ops));
2964 };
2965
2966 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2967 TargetRegionMetadataEmitter);
2968
2969 for (auto *E : OrderedEntries) {
2970 assert(E && "All ordered entries must exist!");
2971 if (auto *CE =
2972 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2973 E)) {
2974 assert(CE->getID() && CE->getAddress() &&
2975 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002976 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002977 } else
2978 llvm_unreachable("Unsupported entry kind.");
2979 }
2980}
2981
2982/// \brief Loads all the offload entries information from the host IR
2983/// metadata.
2984void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2985 // If we are in target mode, load the metadata from the host IR. This code has
2986 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2987
2988 if (!CGM.getLangOpts().OpenMPIsDevice)
2989 return;
2990
2991 if (CGM.getLangOpts().OMPHostIRFile.empty())
2992 return;
2993
2994 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2995 if (Buf.getError())
2996 return;
2997
2998 llvm::LLVMContext C;
2999 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
3000
3001 if (ME.getError())
3002 return;
3003
3004 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3005 if (!MD)
3006 return;
3007
3008 for (auto I : MD->operands()) {
3009 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3010
3011 auto getMDInt = [&](unsigned Idx) {
3012 llvm::ConstantAsMetadata *V =
3013 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3014 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3015 };
3016
3017 auto getMDString = [&](unsigned Idx) {
3018 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3019 return V->getString();
3020 };
3021
3022 switch (getMDInt(0)) {
3023 default:
3024 llvm_unreachable("Unexpected metadata!");
3025 break;
3026 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3027 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3028 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3029 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3030 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003031 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003032 break;
3033 }
3034 }
3035}
3036
Alexey Bataev62b63b12015-03-10 07:28:44 +00003037void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3038 if (!KmpRoutineEntryPtrTy) {
3039 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3040 auto &C = CGM.getContext();
3041 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3042 FunctionProtoType::ExtProtoInfo EPI;
3043 KmpRoutineEntryPtrQTy = C.getPointerType(
3044 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3045 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3046 }
3047}
3048
Alexey Bataevc71a4092015-09-11 10:29:41 +00003049static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3050 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003051 auto *Field = FieldDecl::Create(
3052 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3053 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3054 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3055 Field->setAccess(AS_public);
3056 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003057 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003058}
3059
Samuel Antaoee8fb302016-01-06 13:42:12 +00003060QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3061
3062 // Make sure the type of the entry is already created. This is the type we
3063 // have to create:
3064 // struct __tgt_offload_entry{
3065 // void *addr; // Pointer to the offload entry info.
3066 // // (function or global)
3067 // char *name; // Name of the function or global.
3068 // size_t size; // Size of the entry info (0 if it a function).
3069 // };
3070 if (TgtOffloadEntryQTy.isNull()) {
3071 ASTContext &C = CGM.getContext();
3072 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3073 RD->startDefinition();
3074 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3075 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3076 addFieldToRecordDecl(C, RD, C.getSizeType());
3077 RD->completeDefinition();
3078 TgtOffloadEntryQTy = C.getRecordType(RD);
3079 }
3080 return TgtOffloadEntryQTy;
3081}
3082
3083QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3084 // These are the types we need to build:
3085 // struct __tgt_device_image{
3086 // void *ImageStart; // Pointer to the target code start.
3087 // void *ImageEnd; // Pointer to the target code end.
3088 // // We also add the host entries to the device image, as it may be useful
3089 // // for the target runtime to have access to that information.
3090 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3091 // // the entries.
3092 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3093 // // entries (non inclusive).
3094 // };
3095 if (TgtDeviceImageQTy.isNull()) {
3096 ASTContext &C = CGM.getContext();
3097 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3098 RD->startDefinition();
3099 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3100 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3101 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3102 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3103 RD->completeDefinition();
3104 TgtDeviceImageQTy = C.getRecordType(RD);
3105 }
3106 return TgtDeviceImageQTy;
3107}
3108
3109QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3110 // struct __tgt_bin_desc{
3111 // int32_t NumDevices; // Number of devices supported.
3112 // __tgt_device_image *DeviceImages; // Arrays of device images
3113 // // (one per device).
3114 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3115 // // entries.
3116 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3117 // // entries (non inclusive).
3118 // };
3119 if (TgtBinaryDescriptorQTy.isNull()) {
3120 ASTContext &C = CGM.getContext();
3121 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3122 RD->startDefinition();
3123 addFieldToRecordDecl(
3124 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3125 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3126 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3127 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3128 RD->completeDefinition();
3129 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3130 }
3131 return TgtBinaryDescriptorQTy;
3132}
3133
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003134namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003135struct PrivateHelpersTy {
3136 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3137 const VarDecl *PrivateElemInit)
3138 : Original(Original), PrivateCopy(PrivateCopy),
3139 PrivateElemInit(PrivateElemInit) {}
3140 const VarDecl *Original;
3141 const VarDecl *PrivateCopy;
3142 const VarDecl *PrivateElemInit;
3143};
3144typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003145} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003146
Alexey Bataev9e034042015-05-05 04:05:12 +00003147static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003148createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003149 if (!Privates.empty()) {
3150 auto &C = CGM.getContext();
3151 // Build struct .kmp_privates_t. {
3152 // /* private vars */
3153 // };
3154 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3155 RD->startDefinition();
3156 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003157 auto *VD = Pair.second.Original;
3158 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003159 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003160 auto *FD = addFieldToRecordDecl(C, RD, Type);
3161 if (VD->hasAttrs()) {
3162 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3163 E(VD->getAttrs().end());
3164 I != E; ++I)
3165 FD->addAttr(*I);
3166 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003167 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003168 RD->completeDefinition();
3169 return RD;
3170 }
3171 return nullptr;
3172}
3173
Alexey Bataev9e034042015-05-05 04:05:12 +00003174static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003175createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3176 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003177 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003178 auto &C = CGM.getContext();
3179 // Build struct kmp_task_t {
3180 // void * shareds;
3181 // kmp_routine_entry_t routine;
3182 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003183 // kmp_cmplrdata_t data1;
3184 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003185 // For taskloops additional fields:
3186 // kmp_uint64 lb;
3187 // kmp_uint64 ub;
3188 // kmp_int64 st;
3189 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003190 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003191 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3192 UD->startDefinition();
3193 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3194 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3195 UD->completeDefinition();
3196 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003197 auto *RD = C.buildImplicitRecord("kmp_task_t");
3198 RD->startDefinition();
3199 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3200 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3201 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003202 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3203 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003204 if (isOpenMPTaskLoopDirective(Kind)) {
3205 QualType KmpUInt64Ty =
3206 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3207 QualType KmpInt64Ty =
3208 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3209 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3210 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3211 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3212 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3213 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003214 RD->completeDefinition();
3215 return RD;
3216}
3217
3218static RecordDecl *
3219createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003220 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003221 auto &C = CGM.getContext();
3222 // Build struct kmp_task_t_with_privates {
3223 // kmp_task_t task_data;
3224 // .kmp_privates_t. privates;
3225 // };
3226 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3227 RD->startDefinition();
3228 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003229 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3230 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3231 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003232 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003233 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003234}
3235
3236/// \brief Emit a proxy function which accepts kmp_task_t as the second
3237/// argument.
3238/// \code
3239/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003240/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003241/// For taskloops:
3242/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003243/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003244/// return 0;
3245/// }
3246/// \endcode
3247static llvm::Value *
3248emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003249 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3250 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003251 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003252 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3253 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003254 auto &C = CGM.getContext();
3255 FunctionArgList Args;
3256 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3257 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003258 /*Id=*/nullptr,
3259 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003260 Args.push_back(&GtidArg);
3261 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003262 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003263 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003264 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3265 auto *TaskEntry =
3266 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3267 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003268 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003269 CodeGenFunction CGF(CGM);
3270 CGF.disableDebugInfo();
3271 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3272
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003273 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003274 // tt,
3275 // For taskloops:
3276 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3277 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003278 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003279 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003280 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3281 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3282 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003283 auto *KmpTaskTWithPrivatesQTyRD =
3284 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003285 LValue Base =
3286 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003287 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3288 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3289 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003290 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003291
3292 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3293 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003294 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003295 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003296 CGF.ConvertTypeForMem(SharedsPtrTy));
3297
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003298 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3299 llvm::Value *PrivatesParam;
3300 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3301 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3302 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003303 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003304 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003305 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003306
Alexey Bataev7292c292016-04-25 12:22:29 +00003307 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3308 TaskPrivatesMap,
3309 CGF.Builder
3310 .CreatePointerBitCastOrAddrSpaceCast(
3311 TDBase.getAddress(), CGF.VoidPtrTy)
3312 .getPointer()};
3313 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3314 std::end(CommonArgs));
3315 if (isOpenMPTaskLoopDirective(Kind)) {
3316 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3317 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3318 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3319 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3320 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3321 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3322 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3323 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3324 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3325 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3326 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3327 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3328 CallArgs.push_back(LBParam);
3329 CallArgs.push_back(UBParam);
3330 CallArgs.push_back(StParam);
3331 CallArgs.push_back(LIParam);
3332 }
3333 CallArgs.push_back(SharedsParam);
3334
Alexey Bataev62b63b12015-03-10 07:28:44 +00003335 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3336 CGF.EmitStoreThroughLValue(
3337 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003338 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003339 CGF.FinishFunction();
3340 return TaskEntry;
3341}
3342
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003343static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3344 SourceLocation Loc,
3345 QualType KmpInt32Ty,
3346 QualType KmpTaskTWithPrivatesPtrQTy,
3347 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003348 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003349 FunctionArgList Args;
3350 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3351 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003352 /*Id=*/nullptr,
3353 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003354 Args.push_back(&GtidArg);
3355 Args.push_back(&TaskTypeArg);
3356 FunctionType::ExtInfo Info;
3357 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003358 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003359 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3360 auto *DestructorFn =
3361 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3362 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003363 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3364 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003365 CodeGenFunction CGF(CGM);
3366 CGF.disableDebugInfo();
3367 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3368 Args);
3369
Alexey Bataev31300ed2016-02-04 11:27:03 +00003370 LValue Base = CGF.EmitLoadOfPointerLValue(
3371 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3372 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003373 auto *KmpTaskTWithPrivatesQTyRD =
3374 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3375 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003376 Base = CGF.EmitLValueForField(Base, *FI);
3377 for (auto *Field :
3378 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3379 if (auto DtorKind = Field->getType().isDestructedType()) {
3380 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3381 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3382 }
3383 }
3384 CGF.FinishFunction();
3385 return DestructorFn;
3386}
3387
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003388/// \brief Emit a privates mapping function for correct handling of private and
3389/// firstprivate variables.
3390/// \code
3391/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3392/// **noalias priv1,..., <tyn> **noalias privn) {
3393/// *priv1 = &.privates.priv1;
3394/// ...;
3395/// *privn = &.privates.privn;
3396/// }
3397/// \endcode
3398static llvm::Value *
3399emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003400 ArrayRef<const Expr *> PrivateVars,
3401 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003402 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003403 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003404 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003405 auto &C = CGM.getContext();
3406 FunctionArgList Args;
3407 ImplicitParamDecl TaskPrivatesArg(
3408 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3409 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3410 Args.push_back(&TaskPrivatesArg);
3411 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3412 unsigned Counter = 1;
3413 for (auto *E: PrivateVars) {
3414 Args.push_back(ImplicitParamDecl::Create(
3415 C, /*DC=*/nullptr, Loc,
3416 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3417 .withConst()
3418 .withRestrict()));
3419 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3420 PrivateVarsPos[VD] = Counter;
3421 ++Counter;
3422 }
3423 for (auto *E : FirstprivateVars) {
3424 Args.push_back(ImplicitParamDecl::Create(
3425 C, /*DC=*/nullptr, Loc,
3426 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3427 .withConst()
3428 .withRestrict()));
3429 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3430 PrivateVarsPos[VD] = Counter;
3431 ++Counter;
3432 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003433 for (auto *E: LastprivateVars) {
3434 Args.push_back(ImplicitParamDecl::Create(
3435 C, /*DC=*/nullptr, Loc,
3436 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3437 .withConst()
3438 .withRestrict()));
3439 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3440 PrivateVarsPos[VD] = Counter;
3441 ++Counter;
3442 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003443 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003444 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003445 auto *TaskPrivatesMapTy =
3446 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3447 auto *TaskPrivatesMap = llvm::Function::Create(
3448 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3449 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003450 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3451 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003452 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003453 CodeGenFunction CGF(CGM);
3454 CGF.disableDebugInfo();
3455 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3456 TaskPrivatesMapFnInfo, Args);
3457
3458 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003459 LValue Base = CGF.EmitLoadOfPointerLValue(
3460 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3461 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003462 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3463 Counter = 0;
3464 for (auto *Field : PrivatesQTyRD->fields()) {
3465 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3466 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003467 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003468 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3469 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003470 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003471 ++Counter;
3472 }
3473 CGF.FinishFunction();
3474 return TaskPrivatesMap;
3475}
3476
Alexey Bataev9e034042015-05-05 04:05:12 +00003477static int array_pod_sort_comparator(const PrivateDataTy *P1,
3478 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003479 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3480}
3481
Alexey Bataevf93095a2016-05-05 08:46:22 +00003482/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00003483static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003484 const OMPExecutableDirective &D,
3485 Address KmpTaskSharedsPtr, LValue TDBase,
3486 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3487 QualType SharedsTy, QualType SharedsPtrTy,
3488 const OMPTaskDataTy &Data,
3489 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3490 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003491 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3492 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3493 LValue SrcBase;
3494 if (!Data.FirstprivateVars.empty()) {
3495 SrcBase = CGF.MakeAddrLValue(
3496 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3497 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3498 SharedsTy);
3499 }
3500 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3501 cast<CapturedStmt>(*D.getAssociatedStmt()));
3502 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3503 for (auto &&Pair : Privates) {
3504 auto *VD = Pair.second.PrivateCopy;
3505 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003506 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3507 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003508 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003509 if (auto *Elem = Pair.second.PrivateElemInit) {
3510 auto *OriginalVD = Pair.second.Original;
3511 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3512 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3513 SharedRefLValue = CGF.MakeAddrLValue(
3514 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3515 SharedRefLValue.getType(), AlignmentSource::Decl);
3516 QualType Type = OriginalVD->getType();
3517 if (Type->isArrayType()) {
3518 // Initialize firstprivate array.
3519 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3520 // Perform simple memcpy.
3521 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3522 SharedRefLValue.getAddress(), Type);
3523 } else {
3524 // Initialize firstprivate array using element-by-element
3525 // intialization.
3526 CGF.EmitOMPAggregateAssign(
3527 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3528 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3529 Address SrcElement) {
3530 // Clean up any temporaries needed by the initialization.
3531 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3532 InitScope.addPrivate(
3533 Elem, [SrcElement]() -> Address { return SrcElement; });
3534 (void)InitScope.Privatize();
3535 // Emit initialization for single element.
3536 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3537 CGF, &CapturesInfo);
3538 CGF.EmitAnyExprToMem(Init, DestElement,
3539 Init->getType().getQualifiers(),
3540 /*IsInitializer=*/false);
3541 });
3542 }
3543 } else {
3544 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3545 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3546 return SharedRefLValue.getAddress();
3547 });
3548 (void)InitScope.Privatize();
3549 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3550 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3551 /*capturedByInit=*/false);
3552 }
3553 } else
3554 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3555 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003556 ++FI;
3557 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003558}
3559
3560/// Check if duplication function is required for taskloops.
3561static bool checkInitIsRequired(CodeGenFunction &CGF,
3562 ArrayRef<PrivateDataTy> Privates) {
3563 bool InitRequired = false;
3564 for (auto &&Pair : Privates) {
3565 auto *VD = Pair.second.PrivateCopy;
3566 auto *Init = VD->getAnyInitializer();
3567 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3568 !CGF.isTrivialInitializer(Init));
3569 }
3570 return InitRequired;
3571}
3572
3573
3574/// Emit task_dup function (for initialization of
3575/// private/firstprivate/lastprivate vars and last_iter flag)
3576/// \code
3577/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3578/// lastpriv) {
3579/// // setup lastprivate flag
3580/// task_dst->last = lastpriv;
3581/// // could be constructor calls here...
3582/// }
3583/// \endcode
3584static llvm::Value *
3585emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3586 const OMPExecutableDirective &D,
3587 QualType KmpTaskTWithPrivatesPtrQTy,
3588 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3589 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3590 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3591 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3592 auto &C = CGM.getContext();
3593 FunctionArgList Args;
3594 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc,
3595 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3596 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc,
3597 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3598 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc,
3599 /*Id=*/nullptr, C.IntTy);
3600 Args.push_back(&DstArg);
3601 Args.push_back(&SrcArg);
3602 Args.push_back(&LastprivArg);
3603 auto &TaskDupFnInfo =
3604 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3605 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3606 auto *TaskDup =
3607 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3608 ".omp_task_dup.", &CGM.getModule());
3609 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3610 CodeGenFunction CGF(CGM);
3611 CGF.disableDebugInfo();
3612 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3613
3614 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3615 CGF.GetAddrOfLocalVar(&DstArg),
3616 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3617 // task_dst->liter = lastpriv;
3618 if (WithLastIter) {
3619 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3620 LValue Base = CGF.EmitLValueForField(
3621 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3622 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3623 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3624 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3625 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3626 }
3627
3628 // Emit initial values for private copies (if any).
3629 assert(!Privates.empty());
3630 Address KmpTaskSharedsPtr = Address::invalid();
3631 if (!Data.FirstprivateVars.empty()) {
3632 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3633 CGF.GetAddrOfLocalVar(&SrcArg),
3634 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3635 LValue Base = CGF.EmitLValueForField(
3636 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3637 KmpTaskSharedsPtr = Address(
3638 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3639 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3640 KmpTaskTShareds)),
3641 Loc),
3642 CGF.getNaturalTypeAlignment(SharedsTy));
3643 }
Alexey Bataev8a831592016-05-10 10:36:51 +00003644 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3645 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003646 CGF.FinishFunction();
3647 return TaskDup;
3648}
3649
Alexey Bataev8a831592016-05-10 10:36:51 +00003650/// Checks if destructor function is required to be generated.
3651/// \return true if cleanups are required, false otherwise.
3652static bool
3653checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3654 bool NeedsCleanup = false;
3655 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3656 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3657 for (auto *FD : PrivateRD->fields()) {
3658 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3659 if (NeedsCleanup)
3660 break;
3661 }
3662 return NeedsCleanup;
3663}
3664
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003665CGOpenMPRuntime::TaskResultTy
3666CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3667 const OMPExecutableDirective &D,
3668 llvm::Value *TaskFunction, QualType SharedsTy,
3669 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003670 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00003671 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003672 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003673 auto I = Data.PrivateCopies.begin();
3674 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003675 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3676 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003677 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003678 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3679 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003680 ++I;
3681 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003682 I = Data.FirstprivateCopies.begin();
3683 auto IElemInitRef = Data.FirstprivateInits.begin();
3684 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003685 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3686 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003687 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003688 PrivateHelpersTy(
3689 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3690 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003691 ++I;
3692 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003693 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003694 I = Data.LastprivateCopies.begin();
3695 for (auto *E : Data.LastprivateVars) {
3696 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3697 Privates.push_back(std::make_pair(
3698 C.getDeclAlign(VD),
3699 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3700 /*PrivateElemInit=*/nullptr)));
3701 ++I;
3702 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003703 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3704 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003705 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3706 // Build type kmp_routine_entry_t (if not built yet).
3707 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003708 // Build type kmp_task_t (if not built yet).
3709 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003710 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3711 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003712 }
3713 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003714 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003715 auto *KmpTaskTWithPrivatesQTyRD =
3716 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3717 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3718 QualType KmpTaskTWithPrivatesPtrQTy =
3719 C.getPointerType(KmpTaskTWithPrivatesQTy);
3720 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3721 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003722 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003723 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3724
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003725 // Emit initial values for private copies (if any).
3726 llvm::Value *TaskPrivatesMap = nullptr;
3727 auto *TaskPrivatesMapTy =
3728 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3729 3)
3730 ->getType();
3731 if (!Privates.empty()) {
3732 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003733 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3734 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3735 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003736 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3737 TaskPrivatesMap, TaskPrivatesMapTy);
3738 } else {
3739 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3740 cast<llvm::PointerType>(TaskPrivatesMapTy));
3741 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003742 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3743 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003744 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003745 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3746 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3747 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003748
3749 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3750 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3751 // kmp_routine_entry_t *task_entry);
3752 // Task flags. Format is taken from
3753 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3754 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003755 enum {
3756 TiedFlag = 0x1,
3757 FinalFlag = 0x2,
3758 DestructorsFlag = 0x8,
3759 PriorityFlag = 0x20
3760 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003761 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00003762 bool NeedsCleanup = false;
3763 if (!Privates.empty()) {
3764 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3765 if (NeedsCleanup)
3766 Flags = Flags | DestructorsFlag;
3767 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003768 if (Data.Priority.getInt())
3769 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003770 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003771 Data.Final.getPointer()
3772 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00003773 CGF.Builder.getInt32(FinalFlag),
3774 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003775 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003776 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003777 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003778 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3779 getThreadID(CGF, Loc), TaskFlags,
3780 KmpTaskTWithPrivatesTySize, SharedsSize,
3781 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3782 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003783 auto *NewTask = CGF.EmitRuntimeCall(
3784 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003785 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3786 NewTask, KmpTaskTWithPrivatesPtrTy);
3787 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3788 KmpTaskTWithPrivatesQTy);
3789 LValue TDBase =
3790 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003791 // Fill the data in the resulting kmp_task_t record.
3792 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003793 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003794 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003795 KmpTaskSharedsPtr =
3796 Address(CGF.EmitLoadOfScalar(
3797 CGF.EmitLValueForField(
3798 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3799 KmpTaskTShareds)),
3800 Loc),
3801 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003802 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003803 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003804 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00003805 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003806 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003807 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3808 SharedsTy, SharedsPtrTy, Data, Privates,
3809 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003810 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3811 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3812 Result.TaskDupFn = emitTaskDupFunction(
3813 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3814 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3815 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003816 }
3817 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00003818 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3819 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00003820 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00003821 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3822 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3823 if (NeedsCleanup) {
3824 llvm::Value *DestructorFn = emitDestructorsFunction(
3825 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3826 KmpTaskTWithPrivatesQTy);
3827 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3828 LValue DestructorsLV = CGF.EmitLValueForField(
3829 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3830 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3831 DestructorFn, KmpRoutineEntryPtrTy),
3832 DestructorsLV);
3833 }
3834 // Set priority.
3835 if (Data.Priority.getInt()) {
3836 LValue Data2LV = CGF.EmitLValueForField(
3837 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3838 LValue PriorityLV = CGF.EmitLValueForField(
3839 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3840 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3841 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003842 Result.NewTask = NewTask;
3843 Result.TaskEntry = TaskEntry;
3844 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3845 Result.TDBase = TDBase;
3846 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3847 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00003848}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003849
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003850void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3851 const OMPExecutableDirective &D,
3852 llvm::Value *TaskFunction,
3853 QualType SharedsTy, Address Shareds,
3854 const Expr *IfCond,
3855 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003856 if (!CGF.HaveInsertPoint())
3857 return;
3858
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003859 TaskResultTy Result =
3860 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3861 llvm::Value *NewTask = Result.NewTask;
3862 llvm::Value *TaskEntry = Result.TaskEntry;
3863 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3864 LValue TDBase = Result.TDBase;
3865 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00003866 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003867 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003868 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003869 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00003870 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003871 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003872 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003873 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3874 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003875 QualType FlagsTy =
3876 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003877 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3878 if (KmpDependInfoTy.isNull()) {
3879 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3880 KmpDependInfoRD->startDefinition();
3881 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3882 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3883 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3884 KmpDependInfoRD->completeDefinition();
3885 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003886 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003887 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003888 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003889 // Define type kmp_depend_info[<Dependences.size()>];
3890 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003891 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003892 ArrayType::Normal, /*IndexTypeQuals=*/0);
3893 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00003894 DependenciesArray =
3895 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00003896 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003897 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00003898 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003899 llvm::Value *Size;
3900 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003901 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3902 LValue UpAddrLVal =
3903 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3904 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003905 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003906 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003907 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003908 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3909 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003910 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003911 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003912 auto Base = CGF.MakeAddrLValue(
3913 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003914 KmpDependInfoTy);
3915 // deps[i].base_addr = &<Dependences[i].second>;
3916 auto BaseAddrLVal = CGF.EmitLValueForField(
3917 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003918 CGF.EmitStoreOfScalar(
3919 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3920 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003921 // deps[i].len = sizeof(<Dependences[i].second>);
3922 auto LenLVal = CGF.EmitLValueForField(
3923 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3924 CGF.EmitStoreOfScalar(Size, LenLVal);
3925 // deps[i].flags = <Dependences[i].first>;
3926 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003927 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003928 case OMPC_DEPEND_in:
3929 DepKind = DepIn;
3930 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003931 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003932 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003933 case OMPC_DEPEND_inout:
3934 DepKind = DepInOut;
3935 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003936 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003937 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003938 case OMPC_DEPEND_unknown:
3939 llvm_unreachable("Unknown task dependence type");
3940 }
3941 auto FlagsLVal = CGF.EmitLValueForField(
3942 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3943 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3944 FlagsLVal);
3945 }
John McCall7f416cc2015-09-08 08:05:57 +00003946 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3947 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003948 CGF.VoidPtrTy);
3949 }
3950
Alexey Bataev62b63b12015-03-10 07:28:44 +00003951 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3952 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003953 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3954 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3955 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3956 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003957 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003958 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003959 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3960 llvm::Value *DepTaskArgs[7];
3961 if (NumDependencies) {
3962 DepTaskArgs[0] = UpLoc;
3963 DepTaskArgs[1] = ThreadID;
3964 DepTaskArgs[2] = NewTask;
3965 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3966 DepTaskArgs[4] = DependenciesArray.getPointer();
3967 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3968 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3969 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003970 auto &&ThenCodeGen = [this, Loc, &Data, TDBase, KmpTaskTQTyRD,
Alexey Bataev48591dd2016-04-20 04:01:36 +00003971 NumDependencies, &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003972 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003973 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003974 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3975 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
3976 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
3977 }
John McCall7f416cc2015-09-08 08:05:57 +00003978 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003979 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00003980 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00003981 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003982 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00003983 TaskArgs);
3984 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00003985 // Check if parent region is untied and build return for untied task;
3986 if (auto *Region =
3987 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3988 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00003989 };
John McCall7f416cc2015-09-08 08:05:57 +00003990
3991 llvm::Value *DepWaitTaskArgs[6];
3992 if (NumDependencies) {
3993 DepWaitTaskArgs[0] = UpLoc;
3994 DepWaitTaskArgs[1] = ThreadID;
3995 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3996 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3997 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3998 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3999 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004000 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4001 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4002 PrePostActionTy &) {
4003 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004004 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4005 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4006 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4007 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4008 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004009 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004010 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004011 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004012 // Call proxy_task_entry(gtid, new_task);
4013 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4014 CodeGenFunction &CGF, PrePostActionTy &Action) {
4015 Action.Enter(CGF);
4016 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4017 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4018 };
4019
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004020 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4021 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004022 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4023 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004024 RegionCodeGenTy RCG(CodeGen);
4025 CommonActionTy Action(
4026 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4027 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4028 RCG.setAction(Action);
4029 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004030 };
John McCall7f416cc2015-09-08 08:05:57 +00004031
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004032 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004033 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004034 else {
4035 RegionCodeGenTy ThenRCG(ThenCodeGen);
4036 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004037 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004038}
4039
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004040void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4041 const OMPLoopDirective &D,
4042 llvm::Value *TaskFunction,
4043 QualType SharedsTy, Address Shareds,
4044 const Expr *IfCond,
4045 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004046 if (!CGF.HaveInsertPoint())
4047 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004048 TaskResultTy Result =
4049 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004050 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4051 // libcall.
4052 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4053 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4054 // sched, kmp_uint64 grainsize, void *task_dup);
4055 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4056 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4057 llvm::Value *IfVal;
4058 if (IfCond) {
4059 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4060 /*isSigned=*/true);
4061 } else
4062 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4063
4064 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004065 Result.TDBase,
4066 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004067 auto *LBVar =
4068 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4069 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4070 /*IsInitializer=*/true);
4071 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004072 Result.TDBase,
4073 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004074 auto *UBVar =
4075 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4076 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4077 /*IsInitializer=*/true);
4078 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004079 Result.TDBase,
4080 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004081 auto *StVar =
4082 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4083 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4084 /*IsInitializer=*/true);
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004085 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004086 llvm::Value *TaskArgs[] = {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004087 UpLoc, ThreadID, Result.NewTask, IfVal, LBLVal.getPointer(),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004088 UBLVal.getPointer(), CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004089 llvm::ConstantInt::getSigned(CGF.IntTy, Data.Nogroup ? 1 : 0),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004090 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004091 CGF.IntTy, Data.Schedule.getPointer()
4092 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004093 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004094 Data.Schedule.getPointer()
4095 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004096 /*isSigned=*/false)
4097 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataevf93095a2016-05-05 08:46:22 +00004098 Result.TaskDupFn
4099 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Result.TaskDupFn,
4100 CGF.VoidPtrTy)
4101 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004102 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4103}
4104
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004105/// \brief Emit reduction operation for each element of array (required for
4106/// array sections) LHS op = RHS.
4107/// \param Type Type of array.
4108/// \param LHSVar Variable on the left side of the reduction operation
4109/// (references element of array in original variable).
4110/// \param RHSVar Variable on the right side of the reduction operation
4111/// (references element of array in original variable).
4112/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4113/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004114static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004115 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4116 const VarDecl *RHSVar,
4117 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4118 const Expr *, const Expr *)> &RedOpGen,
4119 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4120 const Expr *UpExpr = nullptr) {
4121 // Perform element-by-element initialization.
4122 QualType ElementTy;
4123 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4124 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4125
4126 // Drill down to the base element type on both arrays.
4127 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4128 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4129
4130 auto RHSBegin = RHSAddr.getPointer();
4131 auto LHSBegin = LHSAddr.getPointer();
4132 // Cast from pointer to array type to pointer to single element.
4133 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4134 // The basic structure here is a while-do loop.
4135 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4136 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4137 auto IsEmpty =
4138 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4139 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4140
4141 // Enter the loop body, making that address the current address.
4142 auto EntryBB = CGF.Builder.GetInsertBlock();
4143 CGF.EmitBlock(BodyBB);
4144
4145 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4146
4147 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4148 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4149 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4150 Address RHSElementCurrent =
4151 Address(RHSElementPHI,
4152 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4153
4154 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4155 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4156 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4157 Address LHSElementCurrent =
4158 Address(LHSElementPHI,
4159 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4160
4161 // Emit copy.
4162 CodeGenFunction::OMPPrivateScope Scope(CGF);
4163 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4164 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4165 Scope.Privatize();
4166 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4167 Scope.ForceCleanup();
4168
4169 // Shift the address forward by one element.
4170 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4171 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4172 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4173 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4174 // Check whether we've reached the end.
4175 auto Done =
4176 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4177 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4178 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4179 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4180
4181 // Done.
4182 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4183}
4184
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004185/// Emit reduction combiner. If the combiner is a simple expression emit it as
4186/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4187/// UDR combiner function.
4188static void emitReductionCombiner(CodeGenFunction &CGF,
4189 const Expr *ReductionOp) {
4190 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4191 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4192 if (auto *DRE =
4193 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4194 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4195 std::pair<llvm::Function *, llvm::Function *> Reduction =
4196 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4197 RValue Func = RValue::get(Reduction.first);
4198 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4199 CGF.EmitIgnoredExpr(ReductionOp);
4200 return;
4201 }
4202 CGF.EmitIgnoredExpr(ReductionOp);
4203}
4204
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004205static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
4206 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004207 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004208 ArrayRef<const Expr *> LHSExprs,
4209 ArrayRef<const Expr *> RHSExprs,
4210 ArrayRef<const Expr *> ReductionOps) {
4211 auto &C = CGM.getContext();
4212
4213 // void reduction_func(void *LHSArg, void *RHSArg);
4214 FunctionArgList Args;
4215 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4216 C.VoidPtrTy);
4217 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4218 C.VoidPtrTy);
4219 Args.push_back(&LHSArg);
4220 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004221 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004222 auto *Fn = llvm::Function::Create(
4223 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4224 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004225 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004226 CodeGenFunction CGF(CGM);
4227 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4228
4229 // Dst = (void*[n])(LHSArg);
4230 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004231 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4232 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4233 ArgsType), CGF.getPointerAlign());
4234 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4235 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4236 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004237
4238 // ...
4239 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4240 // ...
4241 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004242 auto IPriv = Privates.begin();
4243 unsigned Idx = 0;
4244 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004245 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4246 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004247 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004248 });
4249 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4250 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004251 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004252 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004253 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004254 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004255 // Get array size and emit VLA type.
4256 ++Idx;
4257 Address Elem =
4258 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4259 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004260 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4261 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004262 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004263 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004264 CGF.EmitVariablyModifiedType(PrivTy);
4265 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004266 }
4267 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004268 IPriv = Privates.begin();
4269 auto ILHS = LHSExprs.begin();
4270 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004271 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004272 if ((*IPriv)->getType()->isArrayType()) {
4273 // Emit reduction for array section.
4274 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4275 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004276 EmitOMPAggregateReduction(
4277 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4278 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4279 emitReductionCombiner(CGF, E);
4280 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004281 } else
4282 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004283 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004284 ++IPriv;
4285 ++ILHS;
4286 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004287 }
4288 Scope.ForceCleanup();
4289 CGF.FinishFunction();
4290 return Fn;
4291}
4292
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004293static void emitSingleReductionCombiner(CodeGenFunction &CGF,
4294 const Expr *ReductionOp,
4295 const Expr *PrivateRef,
4296 const DeclRefExpr *LHS,
4297 const DeclRefExpr *RHS) {
4298 if (PrivateRef->getType()->isArrayType()) {
4299 // Emit reduction for array section.
4300 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4301 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4302 EmitOMPAggregateReduction(
4303 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4304 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4305 emitReductionCombiner(CGF, ReductionOp);
4306 });
4307 } else
4308 // Emit reduction for array subscript or single variable.
4309 emitReductionCombiner(CGF, ReductionOp);
4310}
4311
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004312void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004313 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004314 ArrayRef<const Expr *> LHSExprs,
4315 ArrayRef<const Expr *> RHSExprs,
4316 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004317 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004318 if (!CGF.HaveInsertPoint())
4319 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004320 // Next code should be emitted for reduction:
4321 //
4322 // static kmp_critical_name lock = { 0 };
4323 //
4324 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4325 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4326 // ...
4327 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4328 // *(Type<n>-1*)rhs[<n>-1]);
4329 // }
4330 //
4331 // ...
4332 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4333 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4334 // RedList, reduce_func, &<lock>)) {
4335 // case 1:
4336 // ...
4337 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4338 // ...
4339 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4340 // break;
4341 // case 2:
4342 // ...
4343 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4344 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004345 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004346 // break;
4347 // default:;
4348 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004349 //
4350 // if SimpleReduction is true, only the next code is generated:
4351 // ...
4352 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4353 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004354
4355 auto &C = CGM.getContext();
4356
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004357 if (SimpleReduction) {
4358 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004359 auto IPriv = Privates.begin();
4360 auto ILHS = LHSExprs.begin();
4361 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004362 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004363 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4364 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004365 ++IPriv;
4366 ++ILHS;
4367 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004368 }
4369 return;
4370 }
4371
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004372 // 1. Build a list of reduction variables.
4373 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004374 auto Size = RHSExprs.size();
4375 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004376 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004377 // Reserve place for array size.
4378 ++Size;
4379 }
4380 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004381 QualType ReductionArrayTy =
4382 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4383 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004384 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004385 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004386 auto IPriv = Privates.begin();
4387 unsigned Idx = 0;
4388 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004389 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004390 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004391 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004392 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004393 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4394 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004395 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004396 // Store array size.
4397 ++Idx;
4398 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4399 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004400 llvm::Value *Size = CGF.Builder.CreateIntCast(
4401 CGF.getVLASize(
4402 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4403 .first,
4404 CGF.SizeTy, /*isSigned=*/false);
4405 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4406 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004407 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004408 }
4409
4410 // 2. Emit reduce_func().
4411 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004412 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4413 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004414
4415 // 3. Create static kmp_critical_name lock = { 0 };
4416 auto *Lock = getCriticalRegionLock(".reduction");
4417
4418 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4419 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004420 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004421 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004422 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00004423 auto *RL =
4424 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
4425 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004426 llvm::Value *Args[] = {
4427 IdentTLoc, // ident_t *<loc>
4428 ThreadId, // i32 <gtid>
4429 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4430 ReductionArrayTySize, // size_type sizeof(RedList)
4431 RL, // void *RedList
4432 ReductionFn, // void (*) (void *, void *) <reduce_func>
4433 Lock // kmp_critical_name *&<lock>
4434 };
4435 auto Res = CGF.EmitRuntimeCall(
4436 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4437 : OMPRTL__kmpc_reduce),
4438 Args);
4439
4440 // 5. Build switch(res)
4441 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4442 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4443
4444 // 6. Build case 1:
4445 // ...
4446 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4447 // ...
4448 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4449 // break;
4450 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4451 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4452 CGF.EmitBlock(Case1BB);
4453
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004454 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4455 llvm::Value *EndArgs[] = {
4456 IdentTLoc, // ident_t *<loc>
4457 ThreadId, // i32 <gtid>
4458 Lock // kmp_critical_name *&<lock>
4459 };
4460 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4461 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004462 auto IPriv = Privates.begin();
4463 auto ILHS = LHSExprs.begin();
4464 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004465 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004466 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4467 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004468 ++IPriv;
4469 ++ILHS;
4470 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004471 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004472 };
4473 RegionCodeGenTy RCG(CodeGen);
4474 CommonActionTy Action(
4475 nullptr, llvm::None,
4476 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4477 : OMPRTL__kmpc_end_reduce),
4478 EndArgs);
4479 RCG.setAction(Action);
4480 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004481
4482 CGF.EmitBranch(DefaultBB);
4483
4484 // 7. Build case 2:
4485 // ...
4486 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4487 // ...
4488 // break;
4489 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4490 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4491 CGF.EmitBlock(Case2BB);
4492
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004493 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4494 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004495 auto ILHS = LHSExprs.begin();
4496 auto IRHS = RHSExprs.begin();
4497 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004498 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004499 const Expr *XExpr = nullptr;
4500 const Expr *EExpr = nullptr;
4501 const Expr *UpExpr = nullptr;
4502 BinaryOperatorKind BO = BO_Comma;
4503 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4504 if (BO->getOpcode() == BO_Assign) {
4505 XExpr = BO->getLHS();
4506 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004507 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004508 }
4509 // Try to emit update expression as a simple atomic.
4510 auto *RHSExpr = UpExpr;
4511 if (RHSExpr) {
4512 // Analyze RHS part of the whole expression.
4513 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4514 RHSExpr->IgnoreParenImpCasts())) {
4515 // If this is a conditional operator, analyze its condition for
4516 // min/max reduction operator.
4517 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004518 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004519 if (auto *BORHS =
4520 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4521 EExpr = BORHS->getRHS();
4522 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004523 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004524 }
4525 if (XExpr) {
4526 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4527 auto &&AtomicRedGen = [BO, VD, IPriv,
4528 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4529 const Expr *EExpr, const Expr *UpExpr) {
4530 LValue X = CGF.EmitLValue(XExpr);
4531 RValue E;
4532 if (EExpr)
4533 E = CGF.EmitAnyExpr(EExpr);
4534 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00004535 X, E, BO, /*IsXLHSInRHSPart=*/true,
4536 llvm::AtomicOrdering::Monotonic, Loc,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004537 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
4538 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4539 PrivateScope.addPrivate(
4540 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4541 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4542 CGF.emitOMPSimpleStore(
4543 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4544 VD->getType().getNonReferenceType(), Loc);
4545 return LHSTemp;
4546 });
4547 (void)PrivateScope.Privatize();
4548 return CGF.EmitAnyExpr(UpExpr);
4549 });
4550 };
4551 if ((*IPriv)->getType()->isArrayType()) {
4552 // Emit atomic reduction for array section.
4553 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4554 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4555 AtomicRedGen, XExpr, EExpr, UpExpr);
4556 } else
4557 // Emit atomic reduction for array subscript or single variable.
4558 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4559 } else {
4560 // Emit as a critical region.
4561 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4562 const Expr *, const Expr *) {
4563 auto &RT = CGF.CGM.getOpenMPRuntime();
4564 RT.emitCriticalRegion(
4565 CGF, ".atomic_reduction",
4566 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4567 Action.Enter(CGF);
4568 emitReductionCombiner(CGF, E);
4569 },
4570 Loc);
4571 };
4572 if ((*IPriv)->getType()->isArrayType()) {
4573 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4574 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4575 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4576 CritRedGen);
4577 } else
4578 CritRedGen(CGF, nullptr, nullptr, nullptr);
4579 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004580 ++ILHS;
4581 ++IRHS;
4582 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004583 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004584 };
4585 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4586 if (!WithNowait) {
4587 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4588 llvm::Value *EndArgs[] = {
4589 IdentTLoc, // ident_t *<loc>
4590 ThreadId, // i32 <gtid>
4591 Lock // kmp_critical_name *&<lock>
4592 };
4593 CommonActionTy Action(nullptr, llvm::None,
4594 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4595 EndArgs);
4596 AtomicRCG.setAction(Action);
4597 AtomicRCG(CGF);
4598 } else
4599 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004600
4601 CGF.EmitBranch(DefaultBB);
4602 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4603}
4604
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004605void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4606 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004607 if (!CGF.HaveInsertPoint())
4608 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004609 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4610 // global_tid);
4611 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4612 // Ignore return result until untied tasks are supported.
4613 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004614 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4615 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004616}
4617
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004618void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004619 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004620 const RegionCodeGenTy &CodeGen,
4621 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004622 if (!CGF.HaveInsertPoint())
4623 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004624 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004625 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004626}
4627
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004628namespace {
4629enum RTCancelKind {
4630 CancelNoreq = 0,
4631 CancelParallel = 1,
4632 CancelLoop = 2,
4633 CancelSections = 3,
4634 CancelTaskgroup = 4
4635};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004636} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004637
4638static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4639 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004640 if (CancelRegion == OMPD_parallel)
4641 CancelKind = CancelParallel;
4642 else if (CancelRegion == OMPD_for)
4643 CancelKind = CancelLoop;
4644 else if (CancelRegion == OMPD_sections)
4645 CancelKind = CancelSections;
4646 else {
4647 assert(CancelRegion == OMPD_taskgroup);
4648 CancelKind = CancelTaskgroup;
4649 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004650 return CancelKind;
4651}
4652
4653void CGOpenMPRuntime::emitCancellationPointCall(
4654 CodeGenFunction &CGF, SourceLocation Loc,
4655 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004656 if (!CGF.HaveInsertPoint())
4657 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004658 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4659 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004660 if (auto *OMPRegionInfo =
4661 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004662 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004663 llvm::Value *Args[] = {
4664 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4665 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004666 // Ignore return result until untied tasks are supported.
4667 auto *Result = CGF.EmitRuntimeCall(
4668 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4669 // if (__kmpc_cancellationpoint()) {
4670 // __kmpc_cancel_barrier();
4671 // exit from construct;
4672 // }
4673 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4674 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4675 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4676 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4677 CGF.EmitBlock(ExitBB);
4678 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004679 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004680 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004681 auto CancelDest =
4682 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004683 CGF.EmitBranchThroughCleanup(CancelDest);
4684 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4685 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004686 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004687}
4688
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004689void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004690 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004691 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004692 if (!CGF.HaveInsertPoint())
4693 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004694 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4695 // kmp_int32 cncl_kind);
4696 if (auto *OMPRegionInfo =
4697 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004698 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4699 PrePostActionTy &) {
4700 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004701 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004702 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004703 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4704 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004705 auto *Result = CGF.EmitRuntimeCall(
4706 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004707 // if (__kmpc_cancel()) {
4708 // __kmpc_cancel_barrier();
4709 // exit from construct;
4710 // }
4711 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4712 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4713 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4714 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4715 CGF.EmitBlock(ExitBB);
4716 // __kmpc_cancel_barrier();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004717 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev87933c72015-09-18 08:07:34 +00004718 // exit from construct;
4719 auto CancelDest =
4720 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4721 CGF.EmitBranchThroughCleanup(CancelDest);
4722 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4723 };
4724 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004725 emitOMPIfClause(CGF, IfCond, ThenGen,
4726 [](CodeGenFunction &, PrePostActionTy &) {});
4727 else {
4728 RegionCodeGenTy ThenRCG(ThenGen);
4729 ThenRCG(CGF);
4730 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004731 }
4732}
Samuel Antaobed3c462015-10-02 16:14:20 +00004733
Samuel Antaoee8fb302016-01-06 13:42:12 +00004734/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004735/// consists of the file and device IDs as well as line number associated with
4736/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004737static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4738 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004739 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004740
4741 auto &SM = C.getSourceManager();
4742
4743 // The loc should be always valid and have a file ID (the user cannot use
4744 // #pragma directives in macros)
4745
4746 assert(Loc.isValid() && "Source location is expected to be always valid.");
4747 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4748
4749 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4750 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4751
4752 llvm::sys::fs::UniqueID ID;
4753 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4754 llvm_unreachable("Source file with target region no longer exists!");
4755
4756 DeviceID = ID.getDevice();
4757 FileID = ID.getFile();
4758 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004759}
4760
4761void CGOpenMPRuntime::emitTargetOutlinedFunction(
4762 const OMPExecutableDirective &D, StringRef ParentName,
4763 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004764 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004765 assert(!ParentName.empty() && "Invalid target region parent name!");
4766
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004767 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4768 IsOffloadEntry, CodeGen);
4769}
4770
4771void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4772 const OMPExecutableDirective &D, StringRef ParentName,
4773 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4774 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004775 // Create a unique name for the entry function using the source location
4776 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004777 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004778 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004779 //
4780 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004781 // mangled name of the function that encloses the target region and BB is the
4782 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004783
4784 unsigned DeviceID;
4785 unsigned FileID;
4786 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004787 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004788 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004789 SmallString<64> EntryFnName;
4790 {
4791 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004792 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4793 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004794 }
4795
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004796 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4797
Samuel Antaobed3c462015-10-02 16:14:20 +00004798 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004799 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004800 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004801
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004802 OutlinedFn =
4803 CGF.GenerateOpenMPCapturedStmtFunction(CS, /*CastValToPtr=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004804
4805 // If this target outline function is not an offload entry, we don't need to
4806 // register it.
4807 if (!IsOffloadEntry)
4808 return;
4809
4810 // The target region ID is used by the runtime library to identify the current
4811 // target region, so it only has to be unique and not necessarily point to
4812 // anything. It could be the pointer to the outlined function that implements
4813 // the target region, but we aren't using that so that the compiler doesn't
4814 // need to keep that, and could therefore inline the host function if proven
4815 // worthwhile during optimization. In the other hand, if emitting code for the
4816 // device, the ID has to be the function address so that it can retrieved from
4817 // the offloading entry and launched by the runtime library. We also mark the
4818 // outlined function to have external linkage in case we are emitting code for
4819 // the device, because these functions will be entry points to the device.
4820
4821 if (CGM.getLangOpts().OpenMPIsDevice) {
4822 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4823 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4824 } else
4825 OutlinedFnID = new llvm::GlobalVariable(
4826 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4827 llvm::GlobalValue::PrivateLinkage,
4828 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4829
4830 // Register the information for the entry associated with this target region.
4831 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004832 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004833}
4834
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004835/// discard all CompoundStmts intervening between two constructs
4836static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4837 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4838 Body = CS->body_front();
4839
4840 return Body;
4841}
4842
Samuel Antaob68e2db2016-03-03 16:20:23 +00004843/// \brief Emit the num_teams clause of an enclosed teams directive at the
4844/// target region scope. If there is no teams directive associated with the
4845/// target directive, or if there is no num_teams clause associated with the
4846/// enclosed teams directive, return nullptr.
4847static llvm::Value *
4848emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4849 CodeGenFunction &CGF,
4850 const OMPExecutableDirective &D) {
4851
4852 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4853 "teams directive expected to be "
4854 "emitted only for the host!");
4855
4856 // FIXME: For the moment we do not support combined directives with target and
4857 // teams, so we do not expect to get any num_teams clause in the provided
4858 // directive. Once we support that, this assertion can be replaced by the
4859 // actual emission of the clause expression.
4860 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4861 "Not expecting clause in directive.");
4862
4863 // If the current target region has a teams region enclosed, we need to get
4864 // the number of teams to pass to the runtime function call. This is done
4865 // by generating the expression in a inlined region. This is required because
4866 // the expression is captured in the enclosing target environment when the
4867 // teams directive is not combined with target.
4868
4869 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4870
4871 // FIXME: Accommodate other combined directives with teams when they become
4872 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004873 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4874 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004875 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4876 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4877 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4878 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4879 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4880 /*IsSigned=*/true);
4881 }
4882
4883 // If we have an enclosed teams directive but no num_teams clause we use
4884 // the default value 0.
4885 return CGF.Builder.getInt32(0);
4886 }
4887
4888 // No teams associated with the directive.
4889 return nullptr;
4890}
4891
4892/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4893/// target region scope. If there is no teams directive associated with the
4894/// target directive, or if there is no thread_limit clause associated with the
4895/// enclosed teams directive, return nullptr.
4896static llvm::Value *
4897emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4898 CodeGenFunction &CGF,
4899 const OMPExecutableDirective &D) {
4900
4901 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4902 "teams directive expected to be "
4903 "emitted only for the host!");
4904
4905 // FIXME: For the moment we do not support combined directives with target and
4906 // teams, so we do not expect to get any thread_limit clause in the provided
4907 // directive. Once we support that, this assertion can be replaced by the
4908 // actual emission of the clause expression.
4909 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4910 "Not expecting clause in directive.");
4911
4912 // If the current target region has a teams region enclosed, we need to get
4913 // the thread limit to pass to the runtime function call. This is done
4914 // by generating the expression in a inlined region. This is required because
4915 // the expression is captured in the enclosing target environment when the
4916 // teams directive is not combined with target.
4917
4918 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4919
4920 // FIXME: Accommodate other combined directives with teams when they become
4921 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004922 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4923 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004924 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4925 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4926 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4927 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4928 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4929 /*IsSigned=*/true);
4930 }
4931
4932 // If we have an enclosed teams directive but no thread_limit clause we use
4933 // the default value 0.
4934 return CGF.Builder.getInt32(0);
4935 }
4936
4937 // No teams associated with the directive.
4938 return nullptr;
4939}
4940
Samuel Antao86ace552016-04-27 22:40:57 +00004941namespace {
4942// \brief Utility to handle information from clauses associated with a given
4943// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
4944// It provides a convenient interface to obtain the information and generate
4945// code for that information.
4946class MappableExprsHandler {
4947public:
4948 /// \brief Values for bit flags used to specify the mapping type for
4949 /// offloading.
4950 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00004951 /// \brief Allocate memory on the device and move data from host to device.
4952 OMP_MAP_TO = 0x01,
4953 /// \brief Allocate memory on the device and move data from device to host.
4954 OMP_MAP_FROM = 0x02,
4955 /// \brief Always perform the requested mapping action on the element, even
4956 /// if it was already mapped before.
4957 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00004958 /// \brief Delete the element from the device environment, ignoring the
4959 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00004960 OMP_MAP_DELETE = 0x08,
4961 /// \brief The element being mapped is a pointer, therefore the pointee
4962 /// should be mapped as well.
4963 OMP_MAP_IS_PTR = 0x10,
4964 /// \brief This flags signals that an argument is the first one relating to
4965 /// a map/private clause expression. For some cases a single
4966 /// map/privatization results in multiple arguments passed to the runtime
4967 /// library.
4968 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaod486f842016-05-26 16:53:38 +00004969 /// \brief This flag signals that the reference being passed is a pointer to
4970 /// private data.
4971 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00004972 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00004973 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00004974 };
4975
4976 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
4977 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
4978
4979private:
4980 /// \brief Directive from where the map clauses were extracted.
4981 const OMPExecutableDirective &Directive;
4982
4983 /// \brief Function the directive is being generated for.
4984 CodeGenFunction &CGF;
4985
Samuel Antaod486f842016-05-26 16:53:38 +00004986 /// \brief Set of all first private variables in the current directive.
4987 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
4988
Samuel Antao86ace552016-04-27 22:40:57 +00004989 llvm::Value *getExprTypeSize(const Expr *E) const {
4990 auto ExprTy = E->getType().getCanonicalType();
4991
4992 // Reference types are ignored for mapping purposes.
4993 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
4994 ExprTy = RefTy->getPointeeType().getCanonicalType();
4995
4996 // Given that an array section is considered a built-in type, we need to
4997 // do the calculation based on the length of the section instead of relying
4998 // on CGF.getTypeSize(E->getType()).
4999 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5000 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5001 OAE->getBase()->IgnoreParenImpCasts())
5002 .getCanonicalType();
5003
5004 // If there is no length associated with the expression, that means we
5005 // are using the whole length of the base.
5006 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5007 return CGF.getTypeSize(BaseTy);
5008
5009 llvm::Value *ElemSize;
5010 if (auto *PTy = BaseTy->getAs<PointerType>())
5011 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5012 else {
5013 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5014 assert(ATy && "Expecting array type if not a pointer type.");
5015 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5016 }
5017
5018 // If we don't have a length at this point, that is because we have an
5019 // array section with a single element.
5020 if (!OAE->getLength())
5021 return ElemSize;
5022
5023 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5024 LengthVal =
5025 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5026 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5027 }
5028 return CGF.getTypeSize(ExprTy);
5029 }
5030
5031 /// \brief Return the corresponding bits for a given map clause modifier. Add
5032 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00005033 /// map as the first one of a series of maps that relate to the same map
5034 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00005035 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5036 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00005037 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00005038 unsigned Bits = 0u;
5039 switch (MapType) {
5040 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00005041 case OMPC_MAP_release:
5042 // alloc and release is the default behavior in the runtime library, i.e.
5043 // if we don't pass any bits alloc/release that is what the runtime is
5044 // going to do. Therefore, we don't need to signal anything for these two
5045 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00005046 break;
5047 case OMPC_MAP_to:
5048 Bits = OMP_MAP_TO;
5049 break;
5050 case OMPC_MAP_from:
5051 Bits = OMP_MAP_FROM;
5052 break;
5053 case OMPC_MAP_tofrom:
5054 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5055 break;
5056 case OMPC_MAP_delete:
5057 Bits = OMP_MAP_DELETE;
5058 break;
Samuel Antao86ace552016-04-27 22:40:57 +00005059 default:
5060 llvm_unreachable("Unexpected map type!");
5061 break;
5062 }
5063 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00005064 Bits |= OMP_MAP_IS_PTR;
5065 if (AddIsFirstFlag)
5066 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00005067 if (MapTypeModifier == OMPC_MAP_always)
5068 Bits |= OMP_MAP_ALWAYS;
5069 return Bits;
5070 }
5071
5072 /// \brief Return true if the provided expression is a final array section. A
5073 /// final array section, is one whose length can't be proved to be one.
5074 bool isFinalArraySectionExpression(const Expr *E) const {
5075 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5076
5077 // It is not an array section and therefore not a unity-size one.
5078 if (!OASE)
5079 return false;
5080
5081 // An array section with no colon always refer to a single element.
5082 if (OASE->getColonLoc().isInvalid())
5083 return false;
5084
5085 auto *Length = OASE->getLength();
5086
5087 // If we don't have a length we have to check if the array has size 1
5088 // for this dimension. Also, we should always expect a length if the
5089 // base type is pointer.
5090 if (!Length) {
5091 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5092 OASE->getBase()->IgnoreParenImpCasts())
5093 .getCanonicalType();
5094 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5095 return ATy->getSize().getSExtValue() != 1;
5096 // If we don't have a constant dimension length, we have to consider
5097 // the current section as having any size, so it is not necessarily
5098 // unitary. If it happen to be unity size, that's user fault.
5099 return true;
5100 }
5101
5102 // Check if the length evaluates to 1.
5103 llvm::APSInt ConstLength;
5104 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5105 return true; // Can have more that size 1.
5106
5107 return ConstLength.getSExtValue() != 1;
5108 }
5109
5110 /// \brief Generate the base pointers, section pointers, sizes and map type
5111 /// bits for the provided map type, map modifier, and expression components.
5112 /// \a IsFirstComponent should be set to true if the provided set of
5113 /// components is the first associated with a capture.
5114 void generateInfoForComponentList(
5115 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5116 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5117 MapValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
5118 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5119 bool IsFirstComponentList) const {
5120
5121 // The following summarizes what has to be generated for each map and the
5122 // types bellow. The generated information is expressed in this order:
5123 // base pointer, section pointer, size, flags
5124 // (to add to the ones that come from the map type and modifier).
5125 //
5126 // double d;
5127 // int i[100];
5128 // float *p;
5129 //
5130 // struct S1 {
5131 // int i;
5132 // float f[50];
5133 // }
5134 // struct S2 {
5135 // int i;
5136 // float f[50];
5137 // S1 s;
5138 // double *p;
5139 // struct S2 *ps;
5140 // }
5141 // S2 s;
5142 // S2 *ps;
5143 //
5144 // map(d)
5145 // &d, &d, sizeof(double), noflags
5146 //
5147 // map(i)
5148 // &i, &i, 100*sizeof(int), noflags
5149 //
5150 // map(i[1:23])
5151 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5152 //
5153 // map(p)
5154 // &p, &p, sizeof(float*), noflags
5155 //
5156 // map(p[1:24])
5157 // p, &p[1], 24*sizeof(float), noflags
5158 //
5159 // map(s)
5160 // &s, &s, sizeof(S2), noflags
5161 //
5162 // map(s.i)
5163 // &s, &(s.i), sizeof(int), noflags
5164 //
5165 // map(s.s.f)
5166 // &s, &(s.i.f), 50*sizeof(int), noflags
5167 //
5168 // map(s.p)
5169 // &s, &(s.p), sizeof(double*), noflags
5170 //
5171 // map(s.p[:22], s.a s.b)
5172 // &s, &(s.p), sizeof(double*), noflags
5173 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5174 //
5175 // map(s.ps)
5176 // &s, &(s.ps), sizeof(S2*), noflags
5177 //
5178 // map(s.ps->s.i)
5179 // &s, &(s.ps), sizeof(S2*), noflags
5180 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5181 //
5182 // map(s.ps->ps)
5183 // &s, &(s.ps), sizeof(S2*), noflags
5184 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5185 //
5186 // map(s.ps->ps->ps)
5187 // &s, &(s.ps), sizeof(S2*), noflags
5188 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5189 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5190 //
5191 // map(s.ps->ps->s.f[:22])
5192 // &s, &(s.ps), sizeof(S2*), noflags
5193 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5194 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5195 //
5196 // map(ps)
5197 // &ps, &ps, sizeof(S2*), noflags
5198 //
5199 // map(ps->i)
5200 // ps, &(ps->i), sizeof(int), noflags
5201 //
5202 // map(ps->s.f)
5203 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5204 //
5205 // map(ps->p)
5206 // ps, &(ps->p), sizeof(double*), noflags
5207 //
5208 // map(ps->p[:22])
5209 // ps, &(ps->p), sizeof(double*), noflags
5210 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5211 //
5212 // map(ps->ps)
5213 // ps, &(ps->ps), sizeof(S2*), noflags
5214 //
5215 // map(ps->ps->s.i)
5216 // ps, &(ps->ps), sizeof(S2*), noflags
5217 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5218 //
5219 // map(ps->ps->ps)
5220 // ps, &(ps->ps), sizeof(S2*), noflags
5221 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5222 //
5223 // map(ps->ps->ps->ps)
5224 // ps, &(ps->ps), sizeof(S2*), noflags
5225 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5226 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5227 //
5228 // map(ps->ps->ps->s.f[:22])
5229 // ps, &(ps->ps), sizeof(S2*), noflags
5230 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5231 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5232 // extra_flag
5233
5234 // Track if the map information being generated is the first for a capture.
5235 bool IsCaptureFirstInfo = IsFirstComponentList;
5236
5237 // Scan the components from the base to the complete expression.
5238 auto CI = Components.rbegin();
5239 auto CE = Components.rend();
5240 auto I = CI;
5241
5242 // Track if the map information being generated is the first for a list of
5243 // components.
5244 bool IsExpressionFirstInfo = true;
5245 llvm::Value *BP = nullptr;
5246
5247 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5248 // The base is the 'this' pointer. The content of the pointer is going
5249 // to be the base of the field being mapped.
5250 BP = CGF.EmitScalarExpr(ME->getBase());
5251 } else {
5252 // The base is the reference to the variable.
5253 // BP = &Var.
5254 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5255 .getPointer();
5256
5257 // If the variable is a pointer and is being dereferenced (i.e. is not
5258 // the last component), the base has to be the pointer itself, not his
5259 // reference.
5260 if (I->getAssociatedDeclaration()->getType()->isAnyPointerType() &&
5261 std::next(I) != CE) {
5262 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(
5263 BP, I->getAssociatedDeclaration()->getType());
5264 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
5265 I->getAssociatedDeclaration()
5266 ->getType()
5267 ->getAs<PointerType>())
5268 .getPointer();
5269
5270 // We do not need to generate individual map information for the
5271 // pointer, it can be associated with the combined storage.
5272 ++I;
5273 }
5274 }
5275
5276 for (; I != CE; ++I) {
5277 auto Next = std::next(I);
5278
5279 // We need to generate the addresses and sizes if this is the last
5280 // component, if the component is a pointer or if it is an array section
5281 // whose length can't be proved to be one. If this is a pointer, it
5282 // becomes the base address for the following components.
5283
5284 // A final array section, is one whose length can't be proved to be one.
5285 bool IsFinalArraySection =
5286 isFinalArraySectionExpression(I->getAssociatedExpression());
5287
5288 // Get information on whether the element is a pointer. Have to do a
5289 // special treatment for array sections given that they are built-in
5290 // types.
5291 const auto *OASE =
5292 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5293 bool IsPointer =
5294 (OASE &&
5295 OMPArraySectionExpr::getBaseOriginalType(OASE)
5296 .getCanonicalType()
5297 ->isAnyPointerType()) ||
5298 I->getAssociatedExpression()->getType()->isAnyPointerType();
5299
5300 if (Next == CE || IsPointer || IsFinalArraySection) {
5301
5302 // If this is not the last component, we expect the pointer to be
5303 // associated with an array expression or member expression.
5304 assert((Next == CE ||
5305 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5306 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5307 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5308 "Unexpected expression");
5309
5310 // Save the base we are currently using.
5311 BasePointers.push_back(BP);
5312
5313 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5314 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5315
5316 Pointers.push_back(LB);
5317 Sizes.push_back(Size);
Samuel Antao6782e942016-05-26 16:48:10 +00005318 // We need to add a pointer flag for each map that comes from the
5319 // same expression except for the first one. We also need to signal
5320 // this map is the first one that relates with the current capture
5321 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00005322 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5323 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00005324 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00005325
5326 // If we have a final array section, we are done with this expression.
5327 if (IsFinalArraySection)
5328 break;
5329
5330 // The pointer becomes the base for the next element.
5331 if (Next != CE)
5332 BP = LB;
5333
5334 IsExpressionFirstInfo = false;
5335 IsCaptureFirstInfo = false;
5336 continue;
5337 }
5338 }
5339 }
5340
Samuel Antaod486f842016-05-26 16:53:38 +00005341 /// \brief Return the adjusted map modifiers if the declaration a capture
5342 /// refers to appears in a first-private clause. This is expected to be used
5343 /// only with directives that start with 'target'.
5344 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5345 unsigned CurrentModifiers) {
5346 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5347
5348 // A first private variable captured by reference will use only the
5349 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5350 // declaration is known as first-private in this handler.
5351 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5352 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5353 MappableExprsHandler::OMP_MAP_TO;
5354
5355 // We didn't modify anything.
5356 return CurrentModifiers;
5357 }
5358
Samuel Antao86ace552016-04-27 22:40:57 +00005359public:
5360 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antaod486f842016-05-26 16:53:38 +00005361 : Directive(Dir), CGF(CGF) {
5362 // Extract firstprivate clause information.
5363 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5364 for (const auto *D : C->varlists())
5365 FirstPrivateDecls.insert(
5366 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
5367 }
Samuel Antao86ace552016-04-27 22:40:57 +00005368
5369 /// \brief Generate all the base pointers, section pointers, sizes and map
5370 /// types for the extracted mappable expressions.
5371 void generateAllInfo(MapValuesArrayTy &BasePointers,
5372 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5373 MapFlagsArrayTy &Types) const {
5374 BasePointers.clear();
5375 Pointers.clear();
5376 Sizes.clear();
5377 Types.clear();
5378
5379 struct MapInfo {
5380 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
5381 OpenMPMapClauseKind MapType;
5382 OpenMPMapClauseKind MapTypeModifier;
5383 };
5384
5385 // We have to process the component lists that relate with the same
5386 // declaration in a single chunk so that we can generate the map flags
5387 // correctly. Therefore, we organize all lists in a map.
5388 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00005389
5390 // Helper function to fill the information map for the different supported
5391 // clauses.
5392 auto &&InfoGen =
5393 [&Info](const ValueDecl *D,
5394 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5395 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier) {
5396 const ValueDecl *VD =
5397 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5398 Info[VD].push_back({L, MapType, MapModifier});
5399 };
5400
Samuel Antao86ace552016-04-27 22:40:57 +00005401 for (auto *C : Directive.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005402 for (auto L : C->component_lists())
5403 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier());
5404 for (auto *C : Directive.getClausesOfKind<OMPToClause>())
5405 for (auto L : C->component_lists())
5406 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown);
5407 for (auto *C : Directive.getClausesOfKind<OMPFromClause>())
5408 for (auto L : C->component_lists())
5409 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown);
Samuel Antao86ace552016-04-27 22:40:57 +00005410
5411 for (auto &M : Info) {
5412 // We need to know when we generate information for the first component
5413 // associated with a capture, because the mapping flags depend on it.
5414 bool IsFirstComponentList = true;
5415 for (MapInfo &L : M.second) {
5416 assert(!L.Components.empty() &&
5417 "Not expecting declaration with no component lists.");
5418 generateInfoForComponentList(L.MapType, L.MapTypeModifier, L.Components,
5419 BasePointers, Pointers, Sizes, Types,
5420 IsFirstComponentList);
5421 IsFirstComponentList = false;
5422 }
5423 }
5424 }
5425
5426 /// \brief Generate the base pointers, section pointers, sizes and map types
5427 /// associated to a given capture.
5428 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
5429 MapValuesArrayTy &BasePointers,
5430 MapValuesArrayTy &Pointers,
5431 MapValuesArrayTy &Sizes,
5432 MapFlagsArrayTy &Types) const {
5433 assert(!Cap->capturesVariableArrayType() &&
5434 "Not expecting to generate map info for a variable array type!");
5435
5436 BasePointers.clear();
5437 Pointers.clear();
5438 Sizes.clear();
5439 Types.clear();
5440
5441 const ValueDecl *VD =
5442 Cap->capturesThis()
5443 ? nullptr
5444 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5445
5446 // We need to know when we generating information for the first component
5447 // associated with a capture, because the mapping flags depend on it.
5448 bool IsFirstComponentList = true;
5449 for (auto *C : Directive.getClausesOfKind<OMPMapClause>())
5450 for (auto L : C->decl_component_lists(VD)) {
5451 assert(L.first == VD &&
5452 "We got information for the wrong declaration??");
5453 assert(!L.second.empty() &&
5454 "Not expecting declaration with no component lists.");
5455 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5456 L.second, BasePointers, Pointers, Sizes,
5457 Types, IsFirstComponentList);
5458 IsFirstComponentList = false;
5459 }
5460
5461 return;
5462 }
Samuel Antaod486f842016-05-26 16:53:38 +00005463
5464 /// \brief Generate the default map information for a given capture \a CI,
5465 /// record field declaration \a RI and captured value \a CV.
5466 void generateDefaultMapInfo(
5467 const CapturedStmt::Capture &CI, const FieldDecl &RI, llvm::Value *CV,
5468 MappableExprsHandler::MapValuesArrayTy &CurBasePointers,
5469 MappableExprsHandler::MapValuesArrayTy &CurPointers,
5470 MappableExprsHandler::MapValuesArrayTy &CurSizes,
5471 MappableExprsHandler::MapFlagsArrayTy &CurMapTypes) {
5472 auto &Ctx = CGF.getContext();
5473
5474 // Do the default mapping.
5475 if (CI.capturesThis()) {
5476 CurBasePointers.push_back(CV);
5477 CurPointers.push_back(CV);
5478 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5479 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5480 // Default map type.
5481 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_TO |
5482 MappableExprsHandler::OMP_MAP_FROM);
5483 } else if (CI.capturesVariableByCopy()) {
5484 if (!RI.getType()->isAnyPointerType()) {
5485 // If the field is not a pointer, we need to save the actual value
5486 // and load it as a void pointer.
5487 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL);
5488 auto DstAddr = CGF.CreateMemTemp(Ctx.getUIntPtrType(),
5489 Twine(CI.getCapturedVar()->getName()) +
5490 ".casted");
5491 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
5492
5493 auto *SrcAddrVal = CGF.EmitScalarConversion(
5494 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
5495 Ctx.getPointerType(RI.getType()), SourceLocation());
5496 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI.getType());
5497
5498 // Store the value using the source type pointer.
5499 CGF.EmitStoreThroughLValue(RValue::get(CV), SrcLV);
5500
5501 // Load the value using the destination type pointer.
5502 CurBasePointers.push_back(
5503 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal());
5504 CurPointers.push_back(CurBasePointers.back());
5505
5506 // Get the size of the type to be used in the map.
5507 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5508 } else {
5509 // Pointers are implicitly mapped with a zero size and no flags
5510 // (other than first map that is added for all implicit maps).
5511 CurMapTypes.push_back(0u);
5512 CurBasePointers.push_back(CV);
5513 CurPointers.push_back(CV);
5514 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5515 }
5516 } else {
5517 assert(CI.capturesVariable() && "Expected captured reference.");
5518 CurBasePointers.push_back(CV);
5519 CurPointers.push_back(CV);
5520
5521 const ReferenceType *PtrTy =
5522 cast<ReferenceType>(RI.getType().getTypePtr());
5523 QualType ElementType = PtrTy->getPointeeType();
5524 CurSizes.push_back(CGF.getTypeSize(ElementType));
5525 // The default map type for a scalar/complex type is 'to' because by
5526 // default the value doesn't have to be retrieved. For an aggregate
5527 // type, the default is 'tofrom'.
5528 CurMapTypes.push_back(ElementType->isAggregateType()
5529 ? (MappableExprsHandler::OMP_MAP_TO |
5530 MappableExprsHandler::OMP_MAP_FROM)
5531 : MappableExprsHandler::OMP_MAP_TO);
5532
5533 // If we have a capture by reference we may need to add the private
5534 // pointer flag if the base declaration shows in some first-private
5535 // clause.
5536 CurMapTypes.back() =
5537 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5538 }
5539 // Every default map produces a single argument, so, it is always the
5540 // first one.
5541 CurMapTypes.back() |= MappableExprsHandler::OMP_MAP_FIRST_REF;
5542 }
Samuel Antao86ace552016-04-27 22:40:57 +00005543};
Samuel Antaodf158d52016-04-27 22:58:19 +00005544
5545enum OpenMPOffloadingReservedDeviceIDs {
5546 /// \brief Device ID if the device was not defined, runtime should get it
5547 /// from environment variables in the spec.
5548 OMP_DEVICEID_UNDEF = -1,
5549};
5550} // anonymous namespace
5551
5552/// \brief Emit the arrays used to pass the captures and map information to the
5553/// offloading runtime library. If there is no map or capture information,
5554/// return nullptr by reference.
5555static void
5556emitOffloadingArrays(CodeGenFunction &CGF, llvm::Value *&BasePointersArray,
5557 llvm::Value *&PointersArray, llvm::Value *&SizesArray,
5558 llvm::Value *&MapTypesArray,
5559 MappableExprsHandler::MapValuesArrayTy &BasePointers,
5560 MappableExprsHandler::MapValuesArrayTy &Pointers,
5561 MappableExprsHandler::MapValuesArrayTy &Sizes,
5562 MappableExprsHandler::MapFlagsArrayTy &MapTypes) {
5563 auto &CGM = CGF.CGM;
5564 auto &Ctx = CGF.getContext();
5565
5566 BasePointersArray = PointersArray = SizesArray = MapTypesArray = nullptr;
5567
5568 if (unsigned PointerNumVal = BasePointers.size()) {
5569 // Detect if we have any capture size requiring runtime evaluation of the
5570 // size so that a constant array could be eventually used.
5571 bool hasRuntimeEvaluationCaptureSize = false;
5572 for (auto *S : Sizes)
5573 if (!isa<llvm::Constant>(S)) {
5574 hasRuntimeEvaluationCaptureSize = true;
5575 break;
5576 }
5577
5578 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
5579 QualType PointerArrayType =
5580 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5581 /*IndexTypeQuals=*/0);
5582
5583 BasePointersArray =
5584 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
5585 PointersArray =
5586 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5587
5588 // If we don't have any VLA types or other types that require runtime
5589 // evaluation, we can use a constant array for the map sizes, otherwise we
5590 // need to fill up the arrays as we do for the pointers.
5591 if (hasRuntimeEvaluationCaptureSize) {
5592 QualType SizeArrayType = Ctx.getConstantArrayType(
5593 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5594 /*IndexTypeQuals=*/0);
5595 SizesArray =
5596 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5597 } else {
5598 // We expect all the sizes to be constant, so we collect them to create
5599 // a constant array.
5600 SmallVector<llvm::Constant *, 16> ConstSizes;
5601 for (auto S : Sizes)
5602 ConstSizes.push_back(cast<llvm::Constant>(S));
5603
5604 auto *SizesArrayInit = llvm::ConstantArray::get(
5605 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5606 auto *SizesArrayGbl = new llvm::GlobalVariable(
5607 CGM.getModule(), SizesArrayInit->getType(),
5608 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5609 SizesArrayInit, ".offload_sizes");
5610 SizesArrayGbl->setUnnamedAddr(true);
5611 SizesArray = SizesArrayGbl;
5612 }
5613
5614 // The map types are always constant so we don't need to generate code to
5615 // fill arrays. Instead, we create an array constant.
5616 llvm::Constant *MapTypesArrayInit =
5617 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5618 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5619 CGM.getModule(), MapTypesArrayInit->getType(),
5620 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5621 MapTypesArrayInit, ".offload_maptypes");
5622 MapTypesArrayGbl->setUnnamedAddr(true);
5623 MapTypesArray = MapTypesArrayGbl;
5624
5625 for (unsigned i = 0; i < PointerNumVal; ++i) {
5626 llvm::Value *BPVal = BasePointers[i];
5627 if (BPVal->getType()->isPointerTy())
5628 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
5629 else {
5630 assert(BPVal->getType()->isIntegerTy() &&
5631 "If not a pointer, the value type must be an integer.");
5632 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
5633 }
5634 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
5635 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), BasePointersArray,
5636 0, i);
5637 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5638 CGF.Builder.CreateStore(BPVal, BPAddr);
5639
5640 llvm::Value *PVal = Pointers[i];
5641 if (PVal->getType()->isPointerTy())
5642 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
5643 else {
5644 assert(PVal->getType()->isIntegerTy() &&
5645 "If not a pointer, the value type must be an integer.");
5646 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
5647 }
5648 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
5649 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray, 0,
5650 i);
5651 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5652 CGF.Builder.CreateStore(PVal, PAddr);
5653
5654 if (hasRuntimeEvaluationCaptureSize) {
5655 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
5656 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
5657 /*Idx0=*/0,
5658 /*Idx1=*/i);
5659 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5660 CGF.Builder.CreateStore(
5661 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5662 SAddr);
5663 }
5664 }
5665 }
5666}
5667/// \brief Emit the arguments to be passed to the runtime library based on the
5668/// arrays of pointers, sizes and map types.
5669static void emitOffloadingArraysArgument(
5670 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5671 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
5672 llvm::Value *&MapTypesArrayArg, llvm::Value *BasePointersArray,
5673 llvm::Value *PointersArray, llvm::Value *SizesArray,
5674 llvm::Value *MapTypesArray, unsigned NumElems) {
5675 auto &CGM = CGF.CGM;
5676 if (NumElems) {
5677 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5678 llvm::ArrayType::get(CGM.VoidPtrTy, NumElems), BasePointersArray,
5679 /*Idx0=*/0, /*Idx1=*/0);
5680 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5681 llvm::ArrayType::get(CGM.VoidPtrTy, NumElems), PointersArray,
5682 /*Idx0=*/0,
5683 /*Idx1=*/0);
5684 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5685 llvm::ArrayType::get(CGM.SizeTy, NumElems), SizesArray,
5686 /*Idx0=*/0, /*Idx1=*/0);
5687 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5688 llvm::ArrayType::get(CGM.Int32Ty, NumElems), MapTypesArray,
5689 /*Idx0=*/0,
5690 /*Idx1=*/0);
5691 } else {
5692 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5693 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5694 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5695 MapTypesArrayArg =
5696 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
5697 }
Samuel Antao86ace552016-04-27 22:40:57 +00005698}
5699
Samuel Antaobed3c462015-10-02 16:14:20 +00005700void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
5701 const OMPExecutableDirective &D,
5702 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00005703 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00005704 const Expr *IfCond, const Expr *Device,
5705 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005706 if (!CGF.HaveInsertPoint())
5707 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00005708
Samuel Antaoee8fb302016-01-06 13:42:12 +00005709 assert(OutlinedFn && "Invalid outlined function!");
5710
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005711 auto &Ctx = CGF.getContext();
5712
Samuel Antao86ace552016-04-27 22:40:57 +00005713 // Fill up the arrays with all the captured variables.
5714 MappableExprsHandler::MapValuesArrayTy KernelArgs;
5715 MappableExprsHandler::MapValuesArrayTy BasePointers;
5716 MappableExprsHandler::MapValuesArrayTy Pointers;
5717 MappableExprsHandler::MapValuesArrayTy Sizes;
5718 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00005719
Samuel Antao86ace552016-04-27 22:40:57 +00005720 MappableExprsHandler::MapValuesArrayTy CurBasePointers;
5721 MappableExprsHandler::MapValuesArrayTy CurPointers;
5722 MappableExprsHandler::MapValuesArrayTy CurSizes;
5723 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
5724
Samuel Antaod486f842016-05-26 16:53:38 +00005725 // Get mappable expression information.
5726 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005727
5728 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5729 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00005730 auto CV = CapturedVars.begin();
5731 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
5732 CE = CS.capture_end();
5733 CI != CE; ++CI, ++RI, ++CV) {
5734 StringRef Name;
5735 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00005736
Samuel Antao86ace552016-04-27 22:40:57 +00005737 CurBasePointers.clear();
5738 CurPointers.clear();
5739 CurSizes.clear();
5740 CurMapTypes.clear();
5741
5742 // VLA sizes are passed to the outlined region by copy and do not have map
5743 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00005744 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00005745 CurBasePointers.push_back(*CV);
5746 CurPointers.push_back(*CV);
5747 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005748 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00005749 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
5750 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005751 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00005752 // If we have any information in the map clause, we use it, otherwise we
5753 // just do a default mapping.
Samuel Antaod486f842016-05-26 16:53:38 +00005754 MEHandler.generateInfoForCapture(CI, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005755 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00005756 if (CurBasePointers.empty())
5757 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
5758 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00005759 }
Samuel Antao86ace552016-04-27 22:40:57 +00005760 // We expect to have at least an element of information for this capture.
5761 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
5762 assert(CurBasePointers.size() == CurPointers.size() &&
5763 CurBasePointers.size() == CurSizes.size() &&
5764 CurBasePointers.size() == CurMapTypes.size() &&
5765 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005766
Samuel Antao86ace552016-04-27 22:40:57 +00005767 // The kernel args are always the first elements of the base pointers
5768 // associated with a capture.
5769 KernelArgs.push_back(CurBasePointers.front());
5770 // We need to append the results of this capture to what we already have.
5771 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
5772 Pointers.append(CurPointers.begin(), CurPointers.end());
5773 Sizes.append(CurSizes.begin(), CurSizes.end());
5774 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00005775 }
5776
5777 // Keep track on whether the host function has to be executed.
5778 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005779 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005780 auto OffloadError = CGF.MakeAddrLValue(
5781 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
5782 OffloadErrorQType);
5783 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
5784 OffloadError);
5785
5786 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antaodf158d52016-04-27 22:58:19 +00005787 auto &&ThenGen = [&Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
5788 OutlinedFnID, OffloadError, OffloadErrorQType,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005789 &D](CodeGenFunction &CGF, PrePostActionTy &) {
5790 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00005791 // Emit the offloading arrays.
Samuel Antaobed3c462015-10-02 16:14:20 +00005792 llvm::Value *BasePointersArray;
5793 llvm::Value *PointersArray;
5794 llvm::Value *SizesArray;
5795 llvm::Value *MapTypesArray;
Samuel Antaodf158d52016-04-27 22:58:19 +00005796 emitOffloadingArrays(CGF, BasePointersArray, PointersArray, SizesArray,
5797 MapTypesArray, BasePointers, Pointers, Sizes,
5798 MapTypes);
5799 emitOffloadingArraysArgument(CGF, BasePointersArray, PointersArray,
5800 SizesArray, MapTypesArray, BasePointersArray,
5801 PointersArray, SizesArray, MapTypesArray,
5802 BasePointers.size());
Samuel Antaobed3c462015-10-02 16:14:20 +00005803
5804 // On top of the arrays that were filled up, the target offloading call
5805 // takes as arguments the device id as well as the host pointer. The host
5806 // pointer is used by the runtime library to identify the current target
5807 // region, so it only has to be unique and not necessarily point to
5808 // anything. It could be the pointer to the outlined function that
5809 // implements the target region, but we aren't using that so that the
5810 // compiler doesn't need to keep that, and could therefore inline the host
5811 // function if proven worthwhile during optimization.
5812
Samuel Antaoee8fb302016-01-06 13:42:12 +00005813 // From this point on, we need to have an ID of the target region defined.
5814 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005815
5816 // Emit device ID if any.
5817 llvm::Value *DeviceID;
5818 if (Device)
5819 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005820 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005821 else
5822 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
5823
Samuel Antaodf158d52016-04-27 22:58:19 +00005824 // Emit the number of elements in the offloading arrays.
5825 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
5826
Samuel Antaob68e2db2016-03-03 16:20:23 +00005827 // Return value of the runtime offloading call.
5828 llvm::Value *Return;
5829
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005830 auto *NumTeams = emitNumTeamsClauseForTargetDirective(RT, CGF, D);
5831 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005832
5833 // If we have NumTeams defined this means that we have an enclosed teams
5834 // region. Therefore we also expect to have ThreadLimit defined. These two
5835 // values should be defined in the presence of a teams directive, regardless
5836 // of having any clauses associated. If the user is using teams but no
5837 // clauses, these two values will be the default that should be passed to
5838 // the runtime library - a 32-bit integer with the value zero.
5839 if (NumTeams) {
5840 assert(ThreadLimit && "Thread limit expression should be available along "
5841 "with number of teams.");
5842 llvm::Value *OffloadingArgs[] = {
5843 DeviceID, OutlinedFnID, PointerNum,
5844 BasePointersArray, PointersArray, SizesArray,
5845 MapTypesArray, NumTeams, ThreadLimit};
5846 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005847 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005848 } else {
5849 llvm::Value *OffloadingArgs[] = {
5850 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
5851 PointersArray, SizesArray, MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005852 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00005853 OffloadingArgs);
5854 }
Samuel Antaobed3c462015-10-02 16:14:20 +00005855
5856 CGF.EmitStoreOfScalar(Return, OffloadError);
5857 };
5858
Samuel Antaoee8fb302016-01-06 13:42:12 +00005859 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005860 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
5861 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00005862 OffloadError);
5863 };
5864
5865 // If we have a target function ID it means that we need to support
5866 // offloading, otherwise, just execute on the host. We need to execute on host
5867 // regardless of the conditional in the if clause if, e.g., the user do not
5868 // specify target triples.
5869 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005870 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00005871 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005872 else {
5873 RegionCodeGenTy ThenRCG(ThenGen);
5874 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005875 }
5876 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005877 RegionCodeGenTy ElseRCG(ElseGen);
5878 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005879 }
Samuel Antaobed3c462015-10-02 16:14:20 +00005880
5881 // Check the error code and execute the host version if required.
5882 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
5883 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
5884 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
5885 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
5886 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
5887
5888 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00005889 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00005890 CGF.EmitBranch(OffloadContBlock);
5891
5892 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005893}
Samuel Antaoee8fb302016-01-06 13:42:12 +00005894
5895void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
5896 StringRef ParentName) {
5897 if (!S)
5898 return;
5899
5900 // If we find a OMP target directive, codegen the outline function and
5901 // register the result.
5902 // FIXME: Add other directives with target when they become supported.
5903 bool isTargetDirective = isa<OMPTargetDirective>(S);
5904
5905 if (isTargetDirective) {
5906 auto *E = cast<OMPExecutableDirective>(S);
5907 unsigned DeviceID;
5908 unsigned FileID;
5909 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005910 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005911 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005912
5913 // Is this a target region that should not be emitted as an entry point? If
5914 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00005915 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
5916 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00005917 return;
5918
5919 llvm::Function *Fn;
5920 llvm::Constant *Addr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005921 std::tie(Fn, Addr) =
5922 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
5923 CGM, cast<OMPTargetDirective>(*E), ParentName,
5924 /*isOffloadEntry=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005925 assert(Fn && Addr && "Target region emission failed.");
5926 return;
5927 }
5928
5929 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00005930 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00005931 return;
5932
5933 scanForTargetRegionsFunctions(
5934 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
5935 ParentName);
5936 return;
5937 }
5938
5939 // If this is a lambda function, look into its body.
5940 if (auto *L = dyn_cast<LambdaExpr>(S))
5941 S = L->getBody();
5942
5943 // Keep looking for target regions recursively.
5944 for (auto *II : S->children())
5945 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005946}
5947
5948bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
5949 auto &FD = *cast<FunctionDecl>(GD.getDecl());
5950
5951 // If emitting code for the host, we do not process FD here. Instead we do
5952 // the normal code generation.
5953 if (!CGM.getLangOpts().OpenMPIsDevice)
5954 return false;
5955
5956 // Try to detect target regions in the function.
5957 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
5958
5959 // We should not emit any function othen that the ones created during the
5960 // scanning. Therefore, we signal that this function is completely dealt
5961 // with.
5962 return true;
5963}
5964
5965bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
5966 if (!CGM.getLangOpts().OpenMPIsDevice)
5967 return false;
5968
5969 // Check if there are Ctors/Dtors in this declaration and look for target
5970 // regions in it. We use the complete variant to produce the kernel name
5971 // mangling.
5972 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
5973 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
5974 for (auto *Ctor : RD->ctors()) {
5975 StringRef ParentName =
5976 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
5977 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
5978 }
5979 auto *Dtor = RD->getDestructor();
5980 if (Dtor) {
5981 StringRef ParentName =
5982 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
5983 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
5984 }
5985 }
5986
5987 // If we are in target mode we do not emit any global (declare target is not
5988 // implemented yet). Therefore we signal that GD was processed in this case.
5989 return true;
5990}
5991
5992bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
5993 auto *VD = GD.getDecl();
5994 if (isa<FunctionDecl>(VD))
5995 return emitTargetFunctions(GD);
5996
5997 return emitTargetGlobalVariable(GD);
5998}
5999
6000llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6001 // If we have offloading in the current module, we need to emit the entries
6002 // now and register the offloading descriptor.
6003 createOffloadEntriesAndInfoMetadata();
6004
6005 // Create and register the offloading binary descriptors. This is the main
6006 // entity that captures all the information about offloading in the current
6007 // compilation unit.
6008 return createOffloadingBinaryDescriptorRegistration();
6009}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006010
6011void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6012 const OMPExecutableDirective &D,
6013 SourceLocation Loc,
6014 llvm::Value *OutlinedFn,
6015 ArrayRef<llvm::Value *> CapturedVars) {
6016 if (!CGF.HaveInsertPoint())
6017 return;
6018
6019 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6020 CodeGenFunction::RunCleanupsScope Scope(CGF);
6021
6022 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6023 llvm::Value *Args[] = {
6024 RTLoc,
6025 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6026 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6027 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6028 RealArgs.append(std::begin(Args), std::end(Args));
6029 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6030
6031 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6032 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6033}
6034
6035void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00006036 const Expr *NumTeams,
6037 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006038 SourceLocation Loc) {
6039 if (!CGF.HaveInsertPoint())
6040 return;
6041
6042 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6043
Carlo Bertollic6872252016-04-04 15:55:02 +00006044 llvm::Value *NumTeamsVal =
6045 (NumTeams)
6046 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6047 CGF.CGM.Int32Ty, /* isSigned = */ true)
6048 : CGF.Builder.getInt32(0);
6049
6050 llvm::Value *ThreadLimitVal =
6051 (ThreadLimit)
6052 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6053 CGF.CGM.Int32Ty, /* isSigned = */ true)
6054 : CGF.Builder.getInt32(0);
6055
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006056 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00006057 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6058 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006059 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6060 PushNumTeamsArgs);
6061}
Samuel Antaodf158d52016-04-27 22:58:19 +00006062
6063void CGOpenMPRuntime::emitTargetDataCalls(CodeGenFunction &CGF,
6064 const OMPExecutableDirective &D,
6065 const Expr *IfCond,
6066 const Expr *Device,
6067 const RegionCodeGenTy &CodeGen) {
6068
6069 if (!CGF.HaveInsertPoint())
6070 return;
6071
6072 llvm::Value *BasePointersArray = nullptr;
6073 llvm::Value *PointersArray = nullptr;
6074 llvm::Value *SizesArray = nullptr;
6075 llvm::Value *MapTypesArray = nullptr;
6076 unsigned NumOfPtrs = 0;
6077
6078 // Generate the code for the opening of the data environment. Capture all the
6079 // arguments of the runtime call by reference because they are used in the
6080 // closing of the region.
6081 auto &&BeginThenGen = [&D, &CGF, &BasePointersArray, &PointersArray,
6082 &SizesArray, &MapTypesArray, Device,
6083 &NumOfPtrs](CodeGenFunction &CGF, PrePostActionTy &) {
6084 // Fill up the arrays with all the mapped variables.
6085 MappableExprsHandler::MapValuesArrayTy BasePointers;
6086 MappableExprsHandler::MapValuesArrayTy Pointers;
6087 MappableExprsHandler::MapValuesArrayTy Sizes;
6088 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6089
6090 // Get map clause information.
6091 MappableExprsHandler MCHandler(D, CGF);
6092 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
6093 NumOfPtrs = BasePointers.size();
6094
6095 // Fill up the arrays and create the arguments.
6096 emitOffloadingArrays(CGF, BasePointersArray, PointersArray, SizesArray,
6097 MapTypesArray, BasePointers, Pointers, Sizes,
6098 MapTypes);
6099
6100 llvm::Value *BasePointersArrayArg = nullptr;
6101 llvm::Value *PointersArrayArg = nullptr;
6102 llvm::Value *SizesArrayArg = nullptr;
6103 llvm::Value *MapTypesArrayArg = nullptr;
6104 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
6105 SizesArrayArg, MapTypesArrayArg,
6106 BasePointersArray, PointersArray, SizesArray,
6107 MapTypesArray, NumOfPtrs);
6108
6109 // Emit device ID if any.
6110 llvm::Value *DeviceID = nullptr;
6111 if (Device)
6112 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6113 CGF.Int32Ty, /*isSigned=*/true);
6114 else
6115 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6116
6117 // Emit the number of elements in the offloading arrays.
6118 auto *PointerNum = CGF.Builder.getInt32(NumOfPtrs);
6119
6120 llvm::Value *OffloadingArgs[] = {
6121 DeviceID, PointerNum, BasePointersArrayArg,
6122 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6123 auto &RT = CGF.CGM.getOpenMPRuntime();
6124 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6125 OffloadingArgs);
6126 };
6127
6128 // Generate code for the closing of the data region.
6129 auto &&EndThenGen = [&CGF, &BasePointersArray, &PointersArray, &SizesArray,
6130 &MapTypesArray, Device,
6131 &NumOfPtrs](CodeGenFunction &CGF, PrePostActionTy &) {
6132 assert(BasePointersArray && PointersArray && SizesArray && MapTypesArray &&
6133 NumOfPtrs && "Invalid data environment closing arguments.");
6134
6135 llvm::Value *BasePointersArrayArg = nullptr;
6136 llvm::Value *PointersArrayArg = nullptr;
6137 llvm::Value *SizesArrayArg = nullptr;
6138 llvm::Value *MapTypesArrayArg = nullptr;
6139 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
6140 SizesArrayArg, MapTypesArrayArg,
6141 BasePointersArray, PointersArray, SizesArray,
6142 MapTypesArray, NumOfPtrs);
6143
6144 // Emit device ID if any.
6145 llvm::Value *DeviceID = nullptr;
6146 if (Device)
6147 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6148 CGF.Int32Ty, /*isSigned=*/true);
6149 else
6150 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6151
6152 // Emit the number of elements in the offloading arrays.
6153 auto *PointerNum = CGF.Builder.getInt32(NumOfPtrs);
6154
6155 llvm::Value *OffloadingArgs[] = {
6156 DeviceID, PointerNum, BasePointersArrayArg,
6157 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6158 auto &RT = CGF.CGM.getOpenMPRuntime();
6159 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6160 OffloadingArgs);
6161 };
6162
6163 // In the event we get an if clause, we don't have to take any action on the
6164 // else side.
6165 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6166
6167 if (IfCond) {
6168 emitOMPIfClause(CGF, IfCond, BeginThenGen, ElseGen);
6169 } else {
6170 RegionCodeGenTy BeginThenRCG(BeginThenGen);
6171 BeginThenRCG(CGF);
6172 }
6173
6174 CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data, CodeGen);
6175
6176 if (IfCond) {
6177 emitOMPIfClause(CGF, IfCond, EndThenGen, ElseGen);
6178 } else {
6179 RegionCodeGenTy EndThenRCG(EndThenGen);
6180 EndThenRCG(CGF);
6181 }
6182}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006183
Samuel Antao8d2d7302016-05-26 18:30:22 +00006184void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00006185 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6186 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006187 if (!CGF.HaveInsertPoint())
6188 return;
6189
Samuel Antao8dd66282016-04-27 23:14:30 +00006190 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00006191 isa<OMPTargetExitDataDirective>(D) ||
6192 isa<OMPTargetUpdateDirective>(D)) &&
6193 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00006194
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006195 // Generate the code for the opening of the data environment.
6196 auto &&ThenGen = [&D, &CGF, Device](CodeGenFunction &CGF, PrePostActionTy &) {
6197 // Fill up the arrays with all the mapped variables.
6198 MappableExprsHandler::MapValuesArrayTy BasePointers;
6199 MappableExprsHandler::MapValuesArrayTy Pointers;
6200 MappableExprsHandler::MapValuesArrayTy Sizes;
6201 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6202
6203 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00006204 MappableExprsHandler MEHandler(D, CGF);
6205 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006206
6207 llvm::Value *BasePointersArrayArg = nullptr;
6208 llvm::Value *PointersArrayArg = nullptr;
6209 llvm::Value *SizesArrayArg = nullptr;
6210 llvm::Value *MapTypesArrayArg = nullptr;
6211
6212 // Fill up the arrays and create the arguments.
6213 emitOffloadingArrays(CGF, BasePointersArrayArg, PointersArrayArg,
6214 SizesArrayArg, MapTypesArrayArg, BasePointers,
6215 Pointers, Sizes, MapTypes);
6216 emitOffloadingArraysArgument(
6217 CGF, BasePointersArrayArg, PointersArrayArg, SizesArrayArg,
6218 MapTypesArrayArg, BasePointersArrayArg, PointersArrayArg, SizesArrayArg,
6219 MapTypesArrayArg, BasePointers.size());
6220
6221 // Emit device ID if any.
6222 llvm::Value *DeviceID = nullptr;
6223 if (Device)
6224 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6225 CGF.Int32Ty, /*isSigned=*/true);
6226 else
6227 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6228
6229 // Emit the number of elements in the offloading arrays.
6230 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6231
6232 llvm::Value *OffloadingArgs[] = {
6233 DeviceID, PointerNum, BasePointersArrayArg,
6234 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Samuel Antao8d2d7302016-05-26 18:30:22 +00006235
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006236 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00006237 // Select the right runtime function call for each expected standalone
6238 // directive.
6239 OpenMPRTLFunction RTLFn;
6240 switch (D.getDirectiveKind()) {
6241 default:
6242 llvm_unreachable("Unexpected standalone target data directive.");
6243 break;
6244 case OMPD_target_enter_data:
6245 RTLFn = OMPRTL__tgt_target_data_begin;
6246 break;
6247 case OMPD_target_exit_data:
6248 RTLFn = OMPRTL__tgt_target_data_end;
6249 break;
6250 case OMPD_target_update:
6251 RTLFn = OMPRTL__tgt_target_data_update;
6252 break;
6253 }
6254 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006255 };
6256
6257 // In the event we get an if clause, we don't have to take any action on the
6258 // else side.
6259 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6260
6261 if (IfCond) {
6262 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6263 } else {
6264 RegionCodeGenTy ThenGenRCG(ThenGen);
6265 ThenGenRCG(CGF);
6266 }
6267}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006268
6269namespace {
6270 /// Kind of parameter in a function with 'declare simd' directive.
6271 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6272 /// Attribute set of the parameter.
6273 struct ParamAttrTy {
6274 ParamKindTy Kind = Vector;
6275 llvm::APSInt StrideOrArg;
6276 llvm::APSInt Alignment;
6277 };
6278} // namespace
6279
6280static unsigned evaluateCDTSize(const FunctionDecl *FD,
6281 ArrayRef<ParamAttrTy> ParamAttrs) {
6282 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6283 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6284 // of that clause. The VLEN value must be power of 2.
6285 // In other case the notion of the function`s "characteristic data type" (CDT)
6286 // is used to compute the vector length.
6287 // CDT is defined in the following order:
6288 // a) For non-void function, the CDT is the return type.
6289 // b) If the function has any non-uniform, non-linear parameters, then the
6290 // CDT is the type of the first such parameter.
6291 // c) If the CDT determined by a) or b) above is struct, union, or class
6292 // type which is pass-by-value (except for the type that maps to the
6293 // built-in complex data type), the characteristic data type is int.
6294 // d) If none of the above three cases is applicable, the CDT is int.
6295 // The VLEN is then determined based on the CDT and the size of vector
6296 // register of that ISA for which current vector version is generated. The
6297 // VLEN is computed using the formula below:
6298 // VLEN = sizeof(vector_register) / sizeof(CDT),
6299 // where vector register size specified in section 3.2.1 Registers and the
6300 // Stack Frame of original AMD64 ABI document.
6301 QualType RetType = FD->getReturnType();
6302 if (RetType.isNull())
6303 return 0;
6304 ASTContext &C = FD->getASTContext();
6305 QualType CDT;
6306 if (!RetType.isNull() && !RetType->isVoidType())
6307 CDT = RetType;
6308 else {
6309 unsigned Offset = 0;
6310 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6311 if (ParamAttrs[Offset].Kind == Vector)
6312 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6313 ++Offset;
6314 }
6315 if (CDT.isNull()) {
6316 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6317 if (ParamAttrs[I + Offset].Kind == Vector) {
6318 CDT = FD->getParamDecl(I)->getType();
6319 break;
6320 }
6321 }
6322 }
6323 }
6324 if (CDT.isNull())
6325 CDT = C.IntTy;
6326 CDT = CDT->getCanonicalTypeUnqualified();
6327 if (CDT->isRecordType() || CDT->isUnionType())
6328 CDT = C.IntTy;
6329 return C.getTypeSize(CDT);
6330}
6331
6332static void
6333emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
6334 llvm::APSInt VLENVal,
6335 ArrayRef<ParamAttrTy> ParamAttrs,
6336 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6337 struct ISADataTy {
6338 char ISA;
6339 unsigned VecRegSize;
6340 };
6341 ISADataTy ISAData[] = {
6342 {
6343 'b', 128
6344 }, // SSE
6345 {
6346 'c', 256
6347 }, // AVX
6348 {
6349 'd', 256
6350 }, // AVX2
6351 {
6352 'e', 512
6353 }, // AVX512
6354 };
6355 llvm::SmallVector<char, 2> Masked;
6356 switch (State) {
6357 case OMPDeclareSimdDeclAttr::BS_Undefined:
6358 Masked.push_back('N');
6359 Masked.push_back('M');
6360 break;
6361 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6362 Masked.push_back('N');
6363 break;
6364 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6365 Masked.push_back('M');
6366 break;
6367 }
6368 for (auto Mask : Masked) {
6369 for (auto &Data : ISAData) {
6370 SmallString<256> Buffer;
6371 llvm::raw_svector_ostream Out(Buffer);
6372 Out << "_ZGV" << Data.ISA << Mask;
6373 if (!VLENVal) {
6374 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6375 evaluateCDTSize(FD, ParamAttrs));
6376 } else
6377 Out << VLENVal;
6378 for (auto &ParamAttr : ParamAttrs) {
6379 switch (ParamAttr.Kind){
6380 case LinearWithVarStride:
6381 Out << 's' << ParamAttr.StrideOrArg;
6382 break;
6383 case Linear:
6384 Out << 'l';
6385 if (!!ParamAttr.StrideOrArg)
6386 Out << ParamAttr.StrideOrArg;
6387 break;
6388 case Uniform:
6389 Out << 'u';
6390 break;
6391 case Vector:
6392 Out << 'v';
6393 break;
6394 }
6395 if (!!ParamAttr.Alignment)
6396 Out << 'a' << ParamAttr.Alignment;
6397 }
6398 Out << '_' << Fn->getName();
6399 Fn->addFnAttr(Out.str());
6400 }
6401 }
6402}
6403
6404void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6405 llvm::Function *Fn) {
6406 ASTContext &C = CGM.getContext();
6407 FD = FD->getCanonicalDecl();
6408 // Map params to their positions in function decl.
6409 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6410 if (isa<CXXMethodDecl>(FD))
6411 ParamPositions.insert({FD, 0});
6412 unsigned ParamPos = ParamPositions.size();
6413 for (auto *P : FD->params()) {
6414 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6415 ++ParamPos;
6416 }
6417 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6418 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6419 // Mark uniform parameters.
6420 for (auto *E : Attr->uniforms()) {
6421 E = E->IgnoreParenImpCasts();
6422 unsigned Pos;
6423 if (isa<CXXThisExpr>(E))
6424 Pos = ParamPositions[FD];
6425 else {
6426 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6427 ->getCanonicalDecl();
6428 Pos = ParamPositions[PVD];
6429 }
6430 ParamAttrs[Pos].Kind = Uniform;
6431 }
6432 // Get alignment info.
6433 auto NI = Attr->alignments_begin();
6434 for (auto *E : Attr->aligneds()) {
6435 E = E->IgnoreParenImpCasts();
6436 unsigned Pos;
6437 QualType ParmTy;
6438 if (isa<CXXThisExpr>(E)) {
6439 Pos = ParamPositions[FD];
6440 ParmTy = E->getType();
6441 } else {
6442 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6443 ->getCanonicalDecl();
6444 Pos = ParamPositions[PVD];
6445 ParmTy = PVD->getType();
6446 }
6447 ParamAttrs[Pos].Alignment =
6448 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6449 : llvm::APSInt::getUnsigned(
6450 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6451 .getQuantity());
6452 ++NI;
6453 }
6454 // Mark linear parameters.
6455 auto SI = Attr->steps_begin();
6456 auto MI = Attr->modifiers_begin();
6457 for (auto *E : Attr->linears()) {
6458 E = E->IgnoreParenImpCasts();
6459 unsigned Pos;
6460 if (isa<CXXThisExpr>(E))
6461 Pos = ParamPositions[FD];
6462 else {
6463 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6464 ->getCanonicalDecl();
6465 Pos = ParamPositions[PVD];
6466 }
6467 auto &ParamAttr = ParamAttrs[Pos];
6468 ParamAttr.Kind = Linear;
6469 if (*SI) {
6470 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6471 Expr::SE_AllowSideEffects)) {
6472 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6473 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6474 ParamAttr.Kind = LinearWithVarStride;
6475 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6476 ParamPositions[StridePVD->getCanonicalDecl()]);
6477 }
6478 }
6479 }
6480 }
6481 ++SI;
6482 ++MI;
6483 }
6484 llvm::APSInt VLENVal;
6485 if (const Expr *VLEN = Attr->getSimdlen())
6486 VLENVal = VLEN->EvaluateKnownConstInt(C);
6487 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6488 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6489 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6490 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6491 }
6492}
Alexey Bataev8b427062016-05-25 12:36:08 +00006493
6494namespace {
6495/// Cleanup action for doacross support.
6496class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6497public:
6498 static const int DoacrossFinArgs = 2;
6499
6500private:
6501 llvm::Value *RTLFn;
6502 llvm::Value *Args[DoacrossFinArgs];
6503
6504public:
6505 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6506 : RTLFn(RTLFn) {
6507 assert(CallArgs.size() == DoacrossFinArgs);
6508 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6509 }
6510 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6511 if (!CGF.HaveInsertPoint())
6512 return;
6513 CGF.EmitRuntimeCall(RTLFn, Args);
6514 }
6515};
6516} // namespace
6517
6518void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6519 const OMPLoopDirective &D) {
6520 if (!CGF.HaveInsertPoint())
6521 return;
6522
6523 ASTContext &C = CGM.getContext();
6524 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6525 RecordDecl *RD;
6526 if (KmpDimTy.isNull()) {
6527 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6528 // kmp_int64 lo; // lower
6529 // kmp_int64 up; // upper
6530 // kmp_int64 st; // stride
6531 // };
6532 RD = C.buildImplicitRecord("kmp_dim");
6533 RD->startDefinition();
6534 addFieldToRecordDecl(C, RD, Int64Ty);
6535 addFieldToRecordDecl(C, RD, Int64Ty);
6536 addFieldToRecordDecl(C, RD, Int64Ty);
6537 RD->completeDefinition();
6538 KmpDimTy = C.getRecordType(RD);
6539 } else
6540 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6541
6542 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6543 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6544 enum { LowerFD = 0, UpperFD, StrideFD };
6545 // Fill dims with data.
6546 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6547 // dims.upper = num_iterations;
6548 LValue UpperLVal =
6549 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6550 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6551 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6552 Int64Ty, D.getNumIterations()->getExprLoc());
6553 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6554 // dims.stride = 1;
6555 LValue StrideLVal =
6556 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6557 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6558 StrideLVal);
6559
6560 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6561 // kmp_int32 num_dims, struct kmp_dim * dims);
6562 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6563 getThreadID(CGF, D.getLocStart()),
6564 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6565 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6566 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6567
6568 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6569 CGF.EmitRuntimeCall(RTLFn, Args);
6570 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6571 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6572 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6573 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6574 llvm::makeArrayRef(FiniArgs));
6575}
6576
6577void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6578 const OMPDependClause *C) {
6579 QualType Int64Ty =
6580 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6581 const Expr *CounterVal = C->getCounterValue();
6582 assert(CounterVal);
6583 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6584 CounterVal->getType(), Int64Ty,
6585 CounterVal->getExprLoc());
6586 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6587 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6588 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6589 getThreadID(CGF, C->getLocStart()),
6590 CntAddr.getPointer()};
6591 llvm::Value *RTLFn;
6592 if (C->getDependencyKind() == OMPC_DEPEND_source)
6593 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6594 else {
6595 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6596 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6597 }
6598 CGF.EmitRuntimeCall(RTLFn, Args);
6599}
6600