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