blob: 8d055b34e7953c7d704084200f51eb58e58adc13 [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"
John McCall5ad74072017-03-02 20:04:19 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000022#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000024#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000028#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000029#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000030#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000031
32using namespace clang;
33using namespace CodeGen;
34
Benjamin Kramerc52193f2014-10-10 13:57:57 +000035namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000036/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000037class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000039 /// \brief Kinds of OpenMP regions used in codegen.
40 enum CGOpenMPRegionKind {
41 /// \brief Region with outlined function for standalone 'parallel'
42 /// directive.
43 ParallelOutlinedRegion,
44 /// \brief Region with outlined function for standalone 'task' directive.
45 TaskOutlinedRegion,
46 /// \brief Region for constructs that do not require function outlining,
47 /// like 'for', 'sections', 'atomic' etc. directives.
48 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000049 /// \brief Region with outlined function for standalone 'target' directive.
50 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 };
Alexey Bataev18095712014-10-10 12:19:54 +000052
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000053 CGOpenMPRegionInfo(const CapturedStmt &CS,
54 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000055 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000058 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000059
60 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000061 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000063 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000064 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000065
66 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000067 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000068 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000069
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000071 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000072
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000073 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000074 /// \return LValue for thread id variable. This LValue always has type int32*.
75 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000076
Alexey Bataev48591dd2016-04-20 04:01:36 +000077 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000079 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080
Alexey Bataev81c7ea02015-07-03 09:56:58 +000081 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82
Alexey Bataev25e5b442015-09-15 12:52:43 +000083 bool hasCancel() const { return HasCancel; }
84
Alexey Bataev18095712014-10-10 12:19:54 +000085 static bool classof(const CGCapturedStmtInfo *Info) {
86 return Info->getKind() == CR_OpenMP;
87 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000088
Alexey Bataev48591dd2016-04-20 04:01:36 +000089 ~CGOpenMPRegionInfo() override = default;
90
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000091protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000092 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000093 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000094 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000095 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096};
Alexey Bataev18095712014-10-10 12:19:54 +000097
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000098/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000099class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000100public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000101 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000102 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000103 OpenMPDirectiveKind Kind, bool HasCancel,
104 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000105 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000107 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000110
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000111 /// \brief Get a variable or parameter for storing global thread id
112 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000113 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114
Alexey Bataev18095712014-10-10 12:19:54 +0000115 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000116 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000117
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000118 static bool classof(const CGCapturedStmtInfo *Info) {
119 return CGOpenMPRegionInfo::classof(Info) &&
120 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121 ParallelOutlinedRegion;
122 }
123
Alexey Bataev18095712014-10-10 12:19:54 +0000124private:
125 /// \brief A variable or parameter storing global thread id for OpenMP
126 /// constructs.
127 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000128 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000129};
130
Alexey Bataev62b63b12015-03-10 07:28:44 +0000131/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000132class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000134 class UntiedTaskActionTy final : public PrePostActionTy {
135 bool Untied;
136 const VarDecl *PartIDVar;
137 const RegionCodeGenTy UntiedCodeGen;
138 llvm::SwitchInst *UntiedSwitch = nullptr;
139
140 public:
141 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142 const RegionCodeGenTy &UntiedCodeGen)
143 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144 void Enter(CodeGenFunction &CGF) override {
145 if (Untied) {
146 // Emit task switching point.
147 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
148 CGF.GetAddrOfLocalVar(PartIDVar),
149 PartIDVar->getType()->castAs<PointerType>());
150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
151 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153 CGF.EmitBlock(DoneBB);
154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157 CGF.Builder.GetInsertBlock());
158 emitUntiedSwitch(CGF);
159 }
160 }
161 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 if (Untied) {
163 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167 PartIdLVal);
168 UntiedCodeGen(CGF);
169 CodeGenFunction::JumpDest CurPoint =
170 CGF.getJumpDestInCurrentScope(".untied.next.");
171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174 CGF.Builder.GetInsertBlock());
175 CGF.EmitBranchThroughCleanup(CurPoint);
176 CGF.EmitBlock(CurPoint.getBlock());
177 }
178 }
179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000182 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000183 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 OpenMPDirectiveKind Kind, bool HasCancel,
185 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000187 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
189 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
Alexey Bataev62b63b12015-03-10 07:28:44 +0000191 /// \brief Get a variable or parameter for storing global thread id
192 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
195 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197
Alexey Bataev62b63b12015-03-10 07:28:44 +0000198 /// \brief Get the name of the capture helper.
199 StringRef getHelperName() const override { return ".omp_outlined."; }
200
Alexey Bataev48591dd2016-04-20 04:01:36 +0000201 void emitUntiedSwitch(CodeGenFunction &CGF) override {
202 Action.emitUntiedSwitch(CGF);
203 }
204
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000205 static bool classof(const CGCapturedStmtInfo *Info) {
206 return CGOpenMPRegionInfo::classof(Info) &&
207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208 TaskOutlinedRegion;
209 }
210
Alexey Bataev62b63b12015-03-10 07:28:44 +0000211private:
212 /// \brief A variable or parameter storing global thread id for OpenMP
213 /// constructs.
214 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000215 /// Action for emitting code for untied tasks.
216 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000217};
218
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000219/// \brief API for inlined captured statement code generation in OpenMP
220/// constructs.
221class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000224 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000225 OpenMPDirectiveKind Kind, bool HasCancel)
226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000229
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000231 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 if (OuterRegionInfo)
233 return OuterRegionInfo->getContextValue();
234 llvm_unreachable("No context value for inlined OpenMP region");
235 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000236
Hans Wennborg7eb54642015-09-10 17:07:54 +0000237 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238 if (OuterRegionInfo) {
239 OuterRegionInfo->setContextValue(V);
240 return;
241 }
242 llvm_unreachable("No context value for inlined OpenMP region");
243 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000244
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000245 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 if (OuterRegionInfo)
248 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000249 // If there is no outer outlined region,no need to lookup in a list of
250 // captured variables, we can use the original one.
251 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000253
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000254 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000255 if (OuterRegionInfo)
256 return OuterRegionInfo->getThisFieldDecl();
257 return nullptr;
258 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000259
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000260 /// \brief Get a variable or parameter for storing global thread id
261 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000262 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 if (OuterRegionInfo)
264 return OuterRegionInfo->getThreadIDVariable();
265 return nullptr;
266 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000268 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000269 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000270 if (auto *OuterRegionInfo = getOldCSI())
271 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000272 llvm_unreachable("No helper name for inlined OpenMP construct");
273 }
274
Alexey Bataev48591dd2016-04-20 04:01:36 +0000275 void emitUntiedSwitch(CodeGenFunction &CGF) override {
276 if (OuterRegionInfo)
277 OuterRegionInfo->emitUntiedSwitch(CGF);
278 }
279
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000280 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
281
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000282 static bool classof(const CGCapturedStmtInfo *Info) {
283 return CGOpenMPRegionInfo::classof(Info) &&
284 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
285 }
286
Alexey Bataev48591dd2016-04-20 04:01:36 +0000287 ~CGOpenMPInlinedRegionInfo() override = default;
288
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000289private:
290 /// \brief CodeGen info about outer OpenMP region.
291 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
292 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000293};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000294
Samuel Antaobed3c462015-10-02 16:14:20 +0000295/// \brief API for captured statement code generation in OpenMP target
296/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000297/// captured fields. The name of the target region has to be unique in a given
298/// application so it is provided by the client, because only the client has
299/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000300class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000301public:
302 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000303 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000304 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000305 /*HasCancel=*/false),
306 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000307
308 /// \brief This is unused for target regions because each starts executing
309 /// with a single thread.
310 const VarDecl *getThreadIDVariable() const override { return nullptr; }
311
312 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000313 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000314
315 static bool classof(const CGCapturedStmtInfo *Info) {
316 return CGOpenMPRegionInfo::classof(Info) &&
317 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
318 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000319
320private:
321 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000322};
323
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000324static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000325 llvm_unreachable("No codegen for expressions");
326}
327/// \brief API for generation of expressions captured in a innermost OpenMP
328/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000329class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000330public:
331 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
332 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
333 OMPD_unknown,
334 /*HasCancel=*/false),
335 PrivScope(CGF) {
336 // Make sure the globals captured in the provided statement are local by
337 // using the privatization logic. We assume the same variable is not
338 // captured more than once.
339 for (auto &C : CS.captures()) {
340 if (!C.capturesVariable() && !C.capturesVariableByCopy())
341 continue;
342
343 const VarDecl *VD = C.getCapturedVar();
344 if (VD->isLocalVarDeclOrParm())
345 continue;
346
347 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
348 /*RefersToEnclosingVariableOrCapture=*/false,
349 VD->getType().getNonReferenceType(), VK_LValue,
350 SourceLocation());
351 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
352 return CGF.EmitLValue(&DRE).getAddress();
353 });
354 }
355 (void)PrivScope.Privatize();
356 }
357
358 /// \brief Lookup the captured field decl for a variable.
359 const FieldDecl *lookup(const VarDecl *VD) const override {
360 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
361 return FD;
362 return nullptr;
363 }
364
365 /// \brief Emit the captured statement body.
366 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
367 llvm_unreachable("No body for expressions");
368 }
369
370 /// \brief Get a variable or parameter for storing global thread id
371 /// inside OpenMP construct.
372 const VarDecl *getThreadIDVariable() const override {
373 llvm_unreachable("No thread id for expressions");
374 }
375
376 /// \brief Get the name of the capture helper.
377 StringRef getHelperName() const override {
378 llvm_unreachable("No helper name for expressions");
379 }
380
381 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
382
383private:
384 /// Private scope to capture global variables.
385 CodeGenFunction::OMPPrivateScope PrivScope;
386};
387
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000388/// \brief RAII for emitting code of OpenMP constructs.
389class InlinedOpenMPRegionRAII {
390 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000391 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
392 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000393
394public:
395 /// \brief Constructs region for combined constructs.
396 /// \param CodeGen Code generation sequence for combined directives. Includes
397 /// a list of functions used for code generation of implicitly inlined
398 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000399 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000400 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000401 : CGF(CGF) {
402 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000403 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
404 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000405 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
406 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
407 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000408 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000409
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000410 ~InlinedOpenMPRegionRAII() {
411 // Restore original CapturedStmtInfo only if we're done with code emission.
412 auto *OldCSI =
413 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
414 delete CGF.CapturedStmtInfo;
415 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000416 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
417 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000418 }
419};
420
Alexey Bataev50b3c952016-02-19 10:38:26 +0000421/// \brief Values for bit flags used in the ident_t to describe the fields.
422/// All enumeric elements are named and described in accordance with the code
423/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000424enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000425 /// \brief Use trampoline for internal microtask.
426 OMP_IDENT_IMD = 0x01,
427 /// \brief Use c-style ident structure.
428 OMP_IDENT_KMPC = 0x02,
429 /// \brief Atomic reduction option for kmpc_reduce.
430 OMP_ATOMIC_REDUCE = 0x10,
431 /// \brief Explicit 'barrier' directive.
432 OMP_IDENT_BARRIER_EXPL = 0x20,
433 /// \brief Implicit barrier in code.
434 OMP_IDENT_BARRIER_IMPL = 0x40,
435 /// \brief Implicit barrier in 'for' directive.
436 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
437 /// \brief Implicit barrier in 'sections' directive.
438 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
439 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000440 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
441 /// Call of __kmp_for_static_init for static loop.
442 OMP_IDENT_WORK_LOOP = 0x200,
443 /// Call of __kmp_for_static_init for sections.
444 OMP_IDENT_WORK_SECTIONS = 0x400,
445 /// Call of __kmp_for_static_init for distribute.
446 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
447 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000448};
449
450/// \brief Describes ident structure that describes a source location.
451/// All descriptions are taken from
452/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
453/// Original structure:
454/// typedef struct ident {
455/// kmp_int32 reserved_1; /**< might be used in Fortran;
456/// see above */
457/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
458/// KMP_IDENT_KMPC identifies this union
459/// member */
460/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
461/// see above */
462///#if USE_ITT_BUILD
463/// /* but currently used for storing
464/// region-specific ITT */
465/// /* contextual information. */
466///#endif /* USE_ITT_BUILD */
467/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
468/// C++ */
469/// char const *psource; /**< String describing the source location.
470/// The string is composed of semi-colon separated
471// fields which describe the source file,
472/// the function and a pair of line numbers that
473/// delimit the construct.
474/// */
475/// } ident_t;
476enum IdentFieldIndex {
477 /// \brief might be used in Fortran
478 IdentField_Reserved_1,
479 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
480 IdentField_Flags,
481 /// \brief Not really used in Fortran any more
482 IdentField_Reserved_2,
483 /// \brief Source[4] in Fortran, do not use for C++
484 IdentField_Reserved_3,
485 /// \brief String describing the source location. The string is composed of
486 /// semi-colon separated fields which describe the source file, the function
487 /// and a pair of line numbers that delimit the construct.
488 IdentField_PSource
489};
490
491/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
492/// the enum sched_type in kmp.h).
493enum OpenMPSchedType {
494 /// \brief Lower bound for default (unordered) versions.
495 OMP_sch_lower = 32,
496 OMP_sch_static_chunked = 33,
497 OMP_sch_static = 34,
498 OMP_sch_dynamic_chunked = 35,
499 OMP_sch_guided_chunked = 36,
500 OMP_sch_runtime = 37,
501 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000502 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000503 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000504 /// \brief Lower bound for 'ordered' versions.
505 OMP_ord_lower = 64,
506 OMP_ord_static_chunked = 65,
507 OMP_ord_static = 66,
508 OMP_ord_dynamic_chunked = 67,
509 OMP_ord_guided_chunked = 68,
510 OMP_ord_runtime = 69,
511 OMP_ord_auto = 70,
512 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000513 /// \brief dist_schedule types
514 OMP_dist_sch_static_chunked = 91,
515 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000516 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
517 /// Set if the monotonic schedule modifier was present.
518 OMP_sch_modifier_monotonic = (1 << 29),
519 /// Set if the nonmonotonic schedule modifier was present.
520 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000521};
522
523enum OpenMPRTLFunction {
524 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
525 /// kmpc_micro microtask, ...);
526 OMPRTL__kmpc_fork_call,
527 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
528 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
529 OMPRTL__kmpc_threadprivate_cached,
530 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
531 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
532 OMPRTL__kmpc_threadprivate_register,
533 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
534 OMPRTL__kmpc_global_thread_num,
535 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
536 // kmp_critical_name *crit);
537 OMPRTL__kmpc_critical,
538 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
539 // global_tid, kmp_critical_name *crit, uintptr_t hint);
540 OMPRTL__kmpc_critical_with_hint,
541 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
542 // kmp_critical_name *crit);
543 OMPRTL__kmpc_end_critical,
544 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
545 // global_tid);
546 OMPRTL__kmpc_cancel_barrier,
547 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
548 OMPRTL__kmpc_barrier,
549 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
550 OMPRTL__kmpc_for_static_fini,
551 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
552 // global_tid);
553 OMPRTL__kmpc_serialized_parallel,
554 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
555 // global_tid);
556 OMPRTL__kmpc_end_serialized_parallel,
557 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
558 // kmp_int32 num_threads);
559 OMPRTL__kmpc_push_num_threads,
560 // Call to void __kmpc_flush(ident_t *loc);
561 OMPRTL__kmpc_flush,
562 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
563 OMPRTL__kmpc_master,
564 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
565 OMPRTL__kmpc_end_master,
566 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
567 // int end_part);
568 OMPRTL__kmpc_omp_taskyield,
569 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
570 OMPRTL__kmpc_single,
571 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
572 OMPRTL__kmpc_end_single,
573 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
574 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
575 // kmp_routine_entry_t *task_entry);
576 OMPRTL__kmpc_omp_task_alloc,
577 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
578 // new_task);
579 OMPRTL__kmpc_omp_task,
580 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
581 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
582 // kmp_int32 didit);
583 OMPRTL__kmpc_copyprivate,
584 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
585 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
586 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
587 OMPRTL__kmpc_reduce,
588 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
589 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
590 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
591 // *lck);
592 OMPRTL__kmpc_reduce_nowait,
593 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
594 // kmp_critical_name *lck);
595 OMPRTL__kmpc_end_reduce,
596 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
597 // kmp_critical_name *lck);
598 OMPRTL__kmpc_end_reduce_nowait,
599 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
600 // kmp_task_t * new_task);
601 OMPRTL__kmpc_omp_task_begin_if0,
602 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
603 // kmp_task_t * new_task);
604 OMPRTL__kmpc_omp_task_complete_if0,
605 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
606 OMPRTL__kmpc_ordered,
607 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
608 OMPRTL__kmpc_end_ordered,
609 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
610 // global_tid);
611 OMPRTL__kmpc_omp_taskwait,
612 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
613 OMPRTL__kmpc_taskgroup,
614 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
615 OMPRTL__kmpc_end_taskgroup,
616 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
617 // int proc_bind);
618 OMPRTL__kmpc_push_proc_bind,
619 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
620 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
621 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
622 OMPRTL__kmpc_omp_task_with_deps,
623 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
624 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
625 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
626 OMPRTL__kmpc_omp_wait_deps,
627 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
628 // global_tid, kmp_int32 cncl_kind);
629 OMPRTL__kmpc_cancellationpoint,
630 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
631 // kmp_int32 cncl_kind);
632 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000633 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
634 // kmp_int32 num_teams, kmp_int32 thread_limit);
635 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000636 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
637 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000638 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000639 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
640 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
641 // sched, kmp_uint64 grainsize, void *task_dup);
642 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000643 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
644 // num_dims, struct kmp_dim *dims);
645 OMPRTL__kmpc_doacross_init,
646 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
647 OMPRTL__kmpc_doacross_fini,
648 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
649 // *vec);
650 OMPRTL__kmpc_doacross_post,
651 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
652 // *vec);
653 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000654 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
655 // *data);
656 OMPRTL__kmpc_task_reduction_init,
657 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
658 // *d);
659 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000660
661 //
662 // Offloading related calls
663 //
664 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
665 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
666 // *arg_types);
667 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000668 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
669 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
670 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
671 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000672 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
673 OMPRTL__tgt_register_lib,
674 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
675 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000676 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
677 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
678 OMPRTL__tgt_target_data_begin,
679 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
680 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
681 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000682 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
683 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
684 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000685};
686
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000687/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
688/// region.
689class CleanupTy final : public EHScopeStack::Cleanup {
690 PrePostActionTy *Action;
691
692public:
693 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
694 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
695 if (!CGF.HaveInsertPoint())
696 return;
697 Action->Exit(CGF);
698 }
699};
700
Hans Wennborg7eb54642015-09-10 17:07:54 +0000701} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000702
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000703void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
704 CodeGenFunction::RunCleanupsScope Scope(CGF);
705 if (PrePostAction) {
706 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
707 Callback(CodeGen, CGF, *PrePostAction);
708 } else {
709 PrePostActionTy Action;
710 Callback(CodeGen, CGF, Action);
711 }
712}
713
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000714/// Check if the combiner is a call to UDR combiner and if it is so return the
715/// UDR decl used for reduction.
716static const OMPDeclareReductionDecl *
717getReductionInit(const Expr *ReductionOp) {
718 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
719 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
720 if (auto *DRE =
721 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
722 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
723 return DRD;
724 return nullptr;
725}
726
727static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
728 const OMPDeclareReductionDecl *DRD,
729 const Expr *InitOp,
730 Address Private, Address Original,
731 QualType Ty) {
732 if (DRD->getInitializer()) {
733 std::pair<llvm::Function *, llvm::Function *> Reduction =
734 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
735 auto *CE = cast<CallExpr>(InitOp);
736 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
737 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
738 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
739 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
740 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
741 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
742 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
743 [=]() -> Address { return Private; });
744 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
745 [=]() -> Address { return Original; });
746 (void)PrivateScope.Privatize();
747 RValue Func = RValue::get(Reduction.second);
748 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
749 CGF.EmitIgnoredExpr(InitOp);
750 } else {
751 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
752 auto *GV = new llvm::GlobalVariable(
753 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
754 llvm::GlobalValue::PrivateLinkage, Init, ".init");
755 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
756 RValue InitRVal;
757 switch (CGF.getEvaluationKind(Ty)) {
758 case TEK_Scalar:
759 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
760 break;
761 case TEK_Complex:
762 InitRVal =
763 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
764 break;
765 case TEK_Aggregate:
766 InitRVal = RValue::getAggregate(LV.getAddress());
767 break;
768 }
769 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
770 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
771 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
772 /*IsInitializer=*/false);
773 }
774}
775
776/// \brief Emit initialization of arrays of complex types.
777/// \param DestAddr Address of the array.
778/// \param Type Type of array.
779/// \param Init Initial expression of array.
780/// \param SrcAddr Address of the original array.
781static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
782 QualType Type, const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000783 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000784 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000785 // Perform element-by-element initialization.
786 QualType ElementTy;
787
788 // Drill down to the base element type on both arrays.
789 auto ArrayTy = Type->getAsArrayTypeUnsafe();
790 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
791 DestAddr =
792 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
793 if (DRD)
794 SrcAddr =
795 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
796
797 llvm::Value *SrcBegin = nullptr;
798 if (DRD)
799 SrcBegin = SrcAddr.getPointer();
800 auto DestBegin = DestAddr.getPointer();
801 // Cast from pointer to array type to pointer to single element.
802 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
803 // The basic structure here is a while-do loop.
804 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
805 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
806 auto IsEmpty =
807 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
808 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
809
810 // Enter the loop body, making that address the current address.
811 auto EntryBB = CGF.Builder.GetInsertBlock();
812 CGF.EmitBlock(BodyBB);
813
814 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
815
816 llvm::PHINode *SrcElementPHI = nullptr;
817 Address SrcElementCurrent = Address::invalid();
818 if (DRD) {
819 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
820 "omp.arraycpy.srcElementPast");
821 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
822 SrcElementCurrent =
823 Address(SrcElementPHI,
824 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
825 }
826 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
827 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
828 DestElementPHI->addIncoming(DestBegin, EntryBB);
829 Address DestElementCurrent =
830 Address(DestElementPHI,
831 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
832
833 // Emit copy.
834 {
835 CodeGenFunction::RunCleanupsScope InitScope(CGF);
836 if (DRD && (DRD->getInitializer() || !Init)) {
837 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
838 SrcElementCurrent, ElementTy);
839 } else
840 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
841 /*IsInitializer=*/false);
842 }
843
844 if (DRD) {
845 // Shift the address forward by one element.
846 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
847 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
848 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
849 }
850
851 // Shift the address forward by one element.
852 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
853 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
854 // Check whether we've reached the end.
855 auto Done =
856 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
857 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
858 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
859
860 // Done.
861 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
862}
863
864LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
865 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
866 return CGF.EmitOMPArraySectionExpr(OASE);
867 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
868 return CGF.EmitLValue(ASE);
869 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
870 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
871 CGF.CapturedStmtInfo &&
872 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
873 E->getType(), VK_LValue, E->getExprLoc());
874 // Store the address of the original variable associated with the LHS
875 // implicit variable.
876 return CGF.EmitLValue(&DRE);
877}
878
879LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
880 const Expr *E) {
881 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
882 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
883 return LValue();
884}
885
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000886void ReductionCodeGen::emitAggregateInitialization(
887 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
888 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000889 // Emit VarDecl with copy init for arrays.
890 // Get the address of the original variable captured in current
891 // captured region.
892 auto *PrivateVD =
893 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000894 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
895 DRD ? ClausesData[N].ReductionOp : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000896 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000897}
898
899ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
900 ArrayRef<const Expr *> Privates,
901 ArrayRef<const Expr *> ReductionOps) {
902 ClausesData.reserve(Shareds.size());
903 SharedAddresses.reserve(Shareds.size());
904 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000905 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000906 auto IPriv = Privates.begin();
907 auto IRed = ReductionOps.begin();
908 for (const auto *Ref : Shareds) {
909 ClausesData.emplace_back(Ref, *IPriv, *IRed);
910 std::advance(IPriv, 1);
911 std::advance(IRed, 1);
912 }
913}
914
915void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
916 assert(SharedAddresses.size() == N &&
917 "Number of generated lvalues must be exactly N.");
918 SharedAddresses.emplace_back(emitSharedLValue(CGF, ClausesData[N].Ref),
919 emitSharedLValueUB(CGF, ClausesData[N].Ref));
920}
921
922void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
923 auto *PrivateVD =
924 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
925 QualType PrivateType = PrivateVD->getType();
926 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
927 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000928 Sizes.emplace_back(
929 CGF.getTypeSize(
930 SharedAddresses[N].first.getType().getNonReferenceType()),
931 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000932 return;
933 }
934 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000935 llvm::Value *SizeInChars;
936 llvm::Type *ElemType =
937 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
938 ->getElementType();
939 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 if (AsArraySection) {
941 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
942 SharedAddresses[N].first.getPointer());
943 Size = CGF.Builder.CreateNUWAdd(
944 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000945 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000946 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000947 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000948 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000949 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000950 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000951 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000952 CodeGenFunction::OpaqueValueMapping OpaqueMap(
953 CGF,
954 cast<OpaqueValueExpr>(
955 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
956 RValue::get(Size));
957 CGF.EmitVariablyModifiedType(PrivateType);
958}
959
960void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
961 llvm::Value *Size) {
962 auto *PrivateVD =
963 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
964 QualType PrivateType = PrivateVD->getType();
965 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
966 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000967 assert(!Size && !Sizes[N].second &&
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000968 "Size should be nullptr for non-variably modified redution "
969 "items.");
970 return;
971 }
972 CodeGenFunction::OpaqueValueMapping OpaqueMap(
973 CGF,
974 cast<OpaqueValueExpr>(
975 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
976 RValue::get(Size));
977 CGF.EmitVariablyModifiedType(PrivateType);
978}
979
980void ReductionCodeGen::emitInitialization(
981 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
982 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
983 assert(SharedAddresses.size() > N && "No variable was generated");
984 auto *PrivateVD =
985 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
986 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
987 QualType PrivateType = PrivateVD->getType();
988 PrivateAddr = CGF.Builder.CreateElementBitCast(
989 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
990 QualType SharedType = SharedAddresses[N].first.getType();
991 SharedLVal = CGF.MakeAddrLValue(
992 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
993 CGF.ConvertTypeForMem(SharedType)),
994 SharedType, SharedAddresses[N].first.getBaseInfo());
995 if (isa<OMPArraySectionExpr>(ClausesData[N].Ref) ||
996 CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000997 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000998 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
999 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1000 PrivateAddr, SharedLVal.getAddress(),
1001 SharedLVal.getType());
1002 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1003 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1004 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1005 PrivateVD->getType().getQualifiers(),
1006 /*IsInitializer=*/false);
1007 }
1008}
1009
1010bool ReductionCodeGen::needCleanups(unsigned N) {
1011 auto *PrivateVD =
1012 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1013 QualType PrivateType = PrivateVD->getType();
1014 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1015 return DTorKind != QualType::DK_none;
1016}
1017
1018void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1019 Address PrivateAddr) {
1020 auto *PrivateVD =
1021 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1022 QualType PrivateType = PrivateVD->getType();
1023 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1024 if (needCleanups(N)) {
1025 PrivateAddr = CGF.Builder.CreateElementBitCast(
1026 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1027 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1028 }
1029}
1030
1031static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1032 LValue BaseLV) {
1033 BaseTy = BaseTy.getNonReferenceType();
1034 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1035 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1036 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1037 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1038 else {
1039 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
1040 BaseTy->castAs<ReferenceType>());
1041 }
1042 BaseTy = BaseTy->getPointeeType();
1043 }
1044 return CGF.MakeAddrLValue(
1045 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1046 CGF.ConvertTypeForMem(ElTy)),
1047 BaseLV.getType(), BaseLV.getBaseInfo());
1048}
1049
1050static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1051 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1052 llvm::Value *Addr) {
1053 Address Tmp = Address::invalid();
1054 Address TopTmp = Address::invalid();
1055 Address MostTopTmp = Address::invalid();
1056 BaseTy = BaseTy.getNonReferenceType();
1057 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1058 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1059 Tmp = CGF.CreateMemTemp(BaseTy);
1060 if (TopTmp.isValid())
1061 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1062 else
1063 MostTopTmp = Tmp;
1064 TopTmp = Tmp;
1065 BaseTy = BaseTy->getPointeeType();
1066 }
1067 llvm::Type *Ty = BaseLVType;
1068 if (Tmp.isValid())
1069 Ty = Tmp.getElementType();
1070 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1071 if (Tmp.isValid()) {
1072 CGF.Builder.CreateStore(Addr, Tmp);
1073 return MostTopTmp;
1074 }
1075 return Address(Addr, BaseLVAlignment);
1076}
1077
1078Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1079 Address PrivateAddr) {
1080 const DeclRefExpr *DE;
1081 const VarDecl *OrigVD = nullptr;
1082 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1083 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1084 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1085 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1086 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1087 Base = TempASE->getBase()->IgnoreParenImpCasts();
1088 DE = cast<DeclRefExpr>(Base);
1089 OrigVD = cast<VarDecl>(DE->getDecl());
1090 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1091 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1092 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1093 Base = TempASE->getBase()->IgnoreParenImpCasts();
1094 DE = cast<DeclRefExpr>(Base);
1095 OrigVD = cast<VarDecl>(DE->getDecl());
1096 }
1097 if (OrigVD) {
1098 BaseDecls.emplace_back(OrigVD);
1099 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1100 LValue BaseLValue =
1101 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1102 OriginalBaseLValue);
1103 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1104 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1105 llvm::Value *Ptr =
1106 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1107 return castToBase(CGF, OrigVD->getType(),
1108 SharedAddresses[N].first.getType(),
1109 OriginalBaseLValue.getPointer()->getType(),
1110 OriginalBaseLValue.getAlignment(), Ptr);
1111 }
1112 BaseDecls.emplace_back(
1113 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1114 return PrivateAddr;
1115}
1116
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001117bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1118 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1119 return DRD && DRD->getInitializer();
1120}
1121
Alexey Bataev18095712014-10-10 12:19:54 +00001122LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001123 return CGF.EmitLoadOfPointerLValue(
1124 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1125 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001126}
1127
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001128void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001129 if (!CGF.HaveInsertPoint())
1130 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001131 // 1.2.2 OpenMP Language Terminology
1132 // Structured block - An executable statement with a single entry at the
1133 // top and a single exit at the bottom.
1134 // The point of exit cannot be a branch out of the structured block.
1135 // longjmp() and throw() must not violate the entry/exit criteria.
1136 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001137 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001138 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001139}
1140
Alexey Bataev62b63b12015-03-10 07:28:44 +00001141LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1142 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001143 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1144 getThreadIDVariable()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001145 LValueBaseInfo(AlignmentSource::Decl, false));
Alexey Bataev62b63b12015-03-10 07:28:44 +00001146}
1147
Alexey Bataev9959db52014-05-06 10:08:46 +00001148CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001149 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001150 IdentTy = llvm::StructType::create(
1151 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1152 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001153 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001154 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001155
1156 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001157}
1158
Alexey Bataev91797552015-03-18 04:13:55 +00001159void CGOpenMPRuntime::clear() {
1160 InternalVars.clear();
1161}
1162
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001163static llvm::Function *
1164emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1165 const Expr *CombinerInitializer, const VarDecl *In,
1166 const VarDecl *Out, bool IsCombiner) {
1167 // void .omp_combiner.(Ty *in, Ty *out);
1168 auto &C = CGM.getContext();
1169 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1170 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001171 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001172 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001173 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001174 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001175 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001176 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001177 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001178 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001179 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1180 auto *Fn = llvm::Function::Create(
1181 FnTy, llvm::GlobalValue::InternalLinkage,
1182 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1183 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001184 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001185 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001186 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001187 CodeGenFunction CGF(CGM);
1188 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1189 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1190 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1191 CodeGenFunction::OMPPrivateScope Scope(CGF);
1192 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1193 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1194 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1195 .getAddress();
1196 });
1197 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1198 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1199 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1200 .getAddress();
1201 });
1202 (void)Scope.Privatize();
1203 CGF.EmitIgnoredExpr(CombinerInitializer);
1204 Scope.ForceCleanup();
1205 CGF.FinishFunction();
1206 return Fn;
1207}
1208
1209void CGOpenMPRuntime::emitUserDefinedReduction(
1210 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1211 if (UDRMap.count(D) > 0)
1212 return;
1213 auto &C = CGM.getContext();
1214 if (!In || !Out) {
1215 In = &C.Idents.get("omp_in");
1216 Out = &C.Idents.get("omp_out");
1217 }
1218 llvm::Function *Combiner = emitCombinerOrInitializer(
1219 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1220 cast<VarDecl>(D->lookup(Out).front()),
1221 /*IsCombiner=*/true);
1222 llvm::Function *Initializer = nullptr;
1223 if (auto *Init = D->getInitializer()) {
1224 if (!Priv || !Orig) {
1225 Priv = &C.Idents.get("omp_priv");
1226 Orig = &C.Idents.get("omp_orig");
1227 }
1228 Initializer = emitCombinerOrInitializer(
1229 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
1230 cast<VarDecl>(D->lookup(Priv).front()),
1231 /*IsCombiner=*/false);
1232 }
1233 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1234 if (CGF) {
1235 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1236 Decls.second.push_back(D);
1237 }
1238}
1239
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001240std::pair<llvm::Function *, llvm::Function *>
1241CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1242 auto I = UDRMap.find(D);
1243 if (I != UDRMap.end())
1244 return I->second;
1245 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1246 return UDRMap.lookup(D);
1247}
1248
John McCall7f416cc2015-09-08 08:05:57 +00001249// Layout information for ident_t.
1250static CharUnits getIdentAlign(CodeGenModule &CGM) {
1251 return CGM.getPointerAlign();
1252}
1253static CharUnits getIdentSize(CodeGenModule &CGM) {
1254 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1255 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1256}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001257static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001258 // All the fields except the last are i32, so this works beautifully.
1259 return unsigned(Field) * CharUnits::fromQuantity(4);
1260}
1261static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001262 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001263 const llvm::Twine &Name = "") {
1264 auto Offset = getOffsetOfIdentField(Field);
1265 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1266}
1267
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001268static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1269 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1270 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1271 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001272 assert(ThreadIDVar->getType()->isPointerType() &&
1273 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001274 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001275 bool HasCancel = false;
1276 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1277 HasCancel = OPD->hasCancel();
1278 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1279 HasCancel = OPSD->hasCancel();
1280 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1281 HasCancel = OPFD->hasCancel();
1282 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001283 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001284 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001285 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001286}
1287
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001288llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1289 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1290 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1291 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1292 return emitParallelOrTeamsOutlinedFunction(
1293 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1294}
1295
1296llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1297 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1298 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1299 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1300 return emitParallelOrTeamsOutlinedFunction(
1301 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1302}
1303
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001304llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1305 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001306 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1307 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1308 bool Tied, unsigned &NumberOfParts) {
1309 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1310 PrePostActionTy &) {
1311 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1312 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1313 llvm::Value *TaskArgs[] = {
1314 UpLoc, ThreadID,
1315 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1316 TaskTVar->getType()->castAs<PointerType>())
1317 .getPointer()};
1318 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1319 };
1320 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1321 UntiedCodeGen);
1322 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001323 assert(!ThreadIDVar->getType()->isPointerType() &&
1324 "thread id variable must be of type kmp_int32 for tasks");
1325 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001326 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001327 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001328 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1329 InnermostKind,
1330 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001331 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001332 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1333 if (!Tied)
1334 NumberOfParts = Action.getNumberOfParts();
1335 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001336}
1337
Alexey Bataev50b3c952016-02-19 10:38:26 +00001338Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001339 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001340 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001341 if (!Entry) {
1342 if (!DefaultOpenMPPSource) {
1343 // Initialize default location for psource field of ident_t structure of
1344 // all ident_t objects. Format is ";file;function;line;column;;".
1345 // Taken from
1346 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1347 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001348 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001349 DefaultOpenMPPSource =
1350 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1351 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001352
John McCall23c9dc62016-11-28 22:18:27 +00001353 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001354 auto fields = builder.beginStruct(IdentTy);
1355 fields.addInt(CGM.Int32Ty, 0);
1356 fields.addInt(CGM.Int32Ty, Flags);
1357 fields.addInt(CGM.Int32Ty, 0);
1358 fields.addInt(CGM.Int32Ty, 0);
1359 fields.add(DefaultOpenMPPSource);
1360 auto DefaultOpenMPLocation =
1361 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1362 llvm::GlobalValue::PrivateLinkage);
1363 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1364
John McCall7f416cc2015-09-08 08:05:57 +00001365 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001366 }
John McCall7f416cc2015-09-08 08:05:57 +00001367 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001368}
1369
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001370llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1371 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001372 unsigned Flags) {
1373 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001374 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001375 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001376 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001377 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001378
1379 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1380
John McCall7f416cc2015-09-08 08:05:57 +00001381 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001382 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1383 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001384 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1385
Alexander Musmanc6388682014-12-15 07:07:06 +00001386 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1387 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001388 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001389 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001390 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1391 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001392 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001393 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001394 LocValue = AI;
1395
1396 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1397 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001398 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001399 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001400 }
1401
1402 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001403 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001404
Alexey Bataevf002aca2014-05-30 05:48:40 +00001405 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1406 if (OMPDebugLoc == nullptr) {
1407 SmallString<128> Buffer2;
1408 llvm::raw_svector_ostream OS2(Buffer2);
1409 // Build debug location
1410 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1411 OS2 << ";" << PLoc.getFilename() << ";";
1412 if (const FunctionDecl *FD =
1413 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1414 OS2 << FD->getQualifiedNameAsString();
1415 }
1416 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1417 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1418 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001419 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001420 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001421 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1422
John McCall7f416cc2015-09-08 08:05:57 +00001423 // Our callers always pass this to a runtime function, so for
1424 // convenience, go ahead and return a naked pointer.
1425 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001426}
1427
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001428llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1429 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001430 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1431
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001432 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001433 // Check whether we've already cached a load of the thread id in this
1434 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001435 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001436 if (I != OpenMPLocThreadIDMap.end()) {
1437 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001438 if (ThreadID != nullptr)
1439 return ThreadID;
1440 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001441 // If exceptions are enabled, do not use parameter to avoid possible crash.
1442 if (!CGF.getInvokeDest()) {
1443 if (auto *OMPRegionInfo =
1444 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1445 if (OMPRegionInfo->getThreadIDVariable()) {
1446 // Check if this an outlined function with thread id passed as argument.
1447 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1448 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1449 // If value loaded in entry block, cache it and use it everywhere in
1450 // function.
1451 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1452 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1453 Elem.second.ThreadID = ThreadID;
1454 }
1455 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001456 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001457 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001458 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001459
1460 // This is not an outlined function region - need to call __kmpc_int32
1461 // kmpc_global_thread_num(ident_t *loc).
1462 // Generate thread id value and cache this value for use across the
1463 // function.
1464 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1465 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1466 ThreadID =
1467 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1468 emitUpdateLocation(CGF, Loc));
1469 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1470 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001471 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001472}
1473
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001474void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001475 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001476 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1477 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001478 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1479 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1480 UDRMap.erase(D);
1481 }
1482 FunctionUDRMap.erase(CGF.CurFn);
1483 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001484}
1485
1486llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001487 if (!IdentTy) {
1488 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001489 return llvm::PointerType::getUnqual(IdentTy);
1490}
1491
1492llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001493 if (!Kmpc_MicroTy) {
1494 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1495 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1496 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1497 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1498 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001499 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1500}
1501
1502llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001503CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001504 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001505 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001506 case OMPRTL__kmpc_fork_call: {
1507 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1508 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001509 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1510 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001511 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001512 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001513 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1514 break;
1515 }
1516 case OMPRTL__kmpc_global_thread_num: {
1517 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001518 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001519 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001520 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001521 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1522 break;
1523 }
Alexey Bataev97720002014-11-11 04:05:39 +00001524 case OMPRTL__kmpc_threadprivate_cached: {
1525 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1526 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1527 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1528 CGM.VoidPtrTy, CGM.SizeTy,
1529 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1530 llvm::FunctionType *FnTy =
1531 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1532 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1533 break;
1534 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001535 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001536 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1537 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001538 llvm::Type *TypeParams[] = {
1539 getIdentTyPointerTy(), CGM.Int32Ty,
1540 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1541 llvm::FunctionType *FnTy =
1542 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1543 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1544 break;
1545 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001546 case OMPRTL__kmpc_critical_with_hint: {
1547 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1548 // kmp_critical_name *crit, uintptr_t hint);
1549 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1550 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1551 CGM.IntPtrTy};
1552 llvm::FunctionType *FnTy =
1553 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1554 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1555 break;
1556 }
Alexey Bataev97720002014-11-11 04:05:39 +00001557 case OMPRTL__kmpc_threadprivate_register: {
1558 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1559 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1560 // typedef void *(*kmpc_ctor)(void *);
1561 auto KmpcCtorTy =
1562 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1563 /*isVarArg*/ false)->getPointerTo();
1564 // typedef void *(*kmpc_cctor)(void *, void *);
1565 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1566 auto KmpcCopyCtorTy =
1567 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1568 /*isVarArg*/ false)->getPointerTo();
1569 // typedef void (*kmpc_dtor)(void *);
1570 auto KmpcDtorTy =
1571 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1572 ->getPointerTo();
1573 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1574 KmpcCopyCtorTy, KmpcDtorTy};
1575 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1576 /*isVarArg*/ false);
1577 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1578 break;
1579 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001580 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001581 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1582 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001583 llvm::Type *TypeParams[] = {
1584 getIdentTyPointerTy(), CGM.Int32Ty,
1585 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1586 llvm::FunctionType *FnTy =
1587 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1588 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1589 break;
1590 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001591 case OMPRTL__kmpc_cancel_barrier: {
1592 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1593 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001594 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1595 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001596 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1597 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001598 break;
1599 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001600 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001601 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001602 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1603 llvm::FunctionType *FnTy =
1604 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1605 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1606 break;
1607 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001608 case OMPRTL__kmpc_for_static_fini: {
1609 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1610 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1611 llvm::FunctionType *FnTy =
1612 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1613 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1614 break;
1615 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001616 case OMPRTL__kmpc_push_num_threads: {
1617 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1618 // kmp_int32 num_threads)
1619 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1620 CGM.Int32Ty};
1621 llvm::FunctionType *FnTy =
1622 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1623 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1624 break;
1625 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001626 case OMPRTL__kmpc_serialized_parallel: {
1627 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1628 // global_tid);
1629 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1630 llvm::FunctionType *FnTy =
1631 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1632 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1633 break;
1634 }
1635 case OMPRTL__kmpc_end_serialized_parallel: {
1636 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1637 // global_tid);
1638 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1639 llvm::FunctionType *FnTy =
1640 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1641 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1642 break;
1643 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001644 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001645 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001646 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1647 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001648 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001649 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1650 break;
1651 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001652 case OMPRTL__kmpc_master: {
1653 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1654 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1655 llvm::FunctionType *FnTy =
1656 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1657 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1658 break;
1659 }
1660 case OMPRTL__kmpc_end_master: {
1661 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1662 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1663 llvm::FunctionType *FnTy =
1664 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1665 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1666 break;
1667 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001668 case OMPRTL__kmpc_omp_taskyield: {
1669 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1670 // int end_part);
1671 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1672 llvm::FunctionType *FnTy =
1673 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1674 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1675 break;
1676 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001677 case OMPRTL__kmpc_single: {
1678 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1679 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1680 llvm::FunctionType *FnTy =
1681 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1682 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1683 break;
1684 }
1685 case OMPRTL__kmpc_end_single: {
1686 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1687 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1688 llvm::FunctionType *FnTy =
1689 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1690 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1691 break;
1692 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001693 case OMPRTL__kmpc_omp_task_alloc: {
1694 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1695 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1696 // kmp_routine_entry_t *task_entry);
1697 assert(KmpRoutineEntryPtrTy != nullptr &&
1698 "Type kmp_routine_entry_t must be created.");
1699 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1700 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1701 // Return void * and then cast to particular kmp_task_t type.
1702 llvm::FunctionType *FnTy =
1703 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1704 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1705 break;
1706 }
1707 case OMPRTL__kmpc_omp_task: {
1708 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1709 // *new_task);
1710 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1711 CGM.VoidPtrTy};
1712 llvm::FunctionType *FnTy =
1713 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1714 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1715 break;
1716 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001717 case OMPRTL__kmpc_copyprivate: {
1718 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001719 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001720 // kmp_int32 didit);
1721 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1722 auto *CpyFnTy =
1723 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001724 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001725 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1726 CGM.Int32Ty};
1727 llvm::FunctionType *FnTy =
1728 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1729 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1730 break;
1731 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001732 case OMPRTL__kmpc_reduce: {
1733 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1734 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1735 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1736 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1737 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1738 /*isVarArg=*/false);
1739 llvm::Type *TypeParams[] = {
1740 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1741 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1742 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1743 llvm::FunctionType *FnTy =
1744 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1745 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1746 break;
1747 }
1748 case OMPRTL__kmpc_reduce_nowait: {
1749 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1750 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1751 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1752 // *lck);
1753 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1754 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1755 /*isVarArg=*/false);
1756 llvm::Type *TypeParams[] = {
1757 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1758 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1759 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1760 llvm::FunctionType *FnTy =
1761 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1762 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1763 break;
1764 }
1765 case OMPRTL__kmpc_end_reduce: {
1766 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1767 // kmp_critical_name *lck);
1768 llvm::Type *TypeParams[] = {
1769 getIdentTyPointerTy(), CGM.Int32Ty,
1770 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1771 llvm::FunctionType *FnTy =
1772 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1773 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1774 break;
1775 }
1776 case OMPRTL__kmpc_end_reduce_nowait: {
1777 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1778 // kmp_critical_name *lck);
1779 llvm::Type *TypeParams[] = {
1780 getIdentTyPointerTy(), CGM.Int32Ty,
1781 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1782 llvm::FunctionType *FnTy =
1783 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1784 RTLFn =
1785 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1786 break;
1787 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001788 case OMPRTL__kmpc_omp_task_begin_if0: {
1789 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1790 // *new_task);
1791 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1792 CGM.VoidPtrTy};
1793 llvm::FunctionType *FnTy =
1794 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1795 RTLFn =
1796 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1797 break;
1798 }
1799 case OMPRTL__kmpc_omp_task_complete_if0: {
1800 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1801 // *new_task);
1802 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1803 CGM.VoidPtrTy};
1804 llvm::FunctionType *FnTy =
1805 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1806 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1807 /*Name=*/"__kmpc_omp_task_complete_if0");
1808 break;
1809 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001810 case OMPRTL__kmpc_ordered: {
1811 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1812 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1813 llvm::FunctionType *FnTy =
1814 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1815 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1816 break;
1817 }
1818 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001819 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001820 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1821 llvm::FunctionType *FnTy =
1822 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1823 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1824 break;
1825 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001826 case OMPRTL__kmpc_omp_taskwait: {
1827 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1828 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1829 llvm::FunctionType *FnTy =
1830 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1831 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1832 break;
1833 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001834 case OMPRTL__kmpc_taskgroup: {
1835 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1836 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1837 llvm::FunctionType *FnTy =
1838 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1839 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1840 break;
1841 }
1842 case OMPRTL__kmpc_end_taskgroup: {
1843 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1844 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1845 llvm::FunctionType *FnTy =
1846 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1847 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1848 break;
1849 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001850 case OMPRTL__kmpc_push_proc_bind: {
1851 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1852 // int proc_bind)
1853 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1854 llvm::FunctionType *FnTy =
1855 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1856 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1857 break;
1858 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001859 case OMPRTL__kmpc_omp_task_with_deps: {
1860 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1861 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1862 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1863 llvm::Type *TypeParams[] = {
1864 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1865 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1866 llvm::FunctionType *FnTy =
1867 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1868 RTLFn =
1869 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1870 break;
1871 }
1872 case OMPRTL__kmpc_omp_wait_deps: {
1873 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1874 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1875 // kmp_depend_info_t *noalias_dep_list);
1876 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1877 CGM.Int32Ty, CGM.VoidPtrTy,
1878 CGM.Int32Ty, CGM.VoidPtrTy};
1879 llvm::FunctionType *FnTy =
1880 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1881 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1882 break;
1883 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001884 case OMPRTL__kmpc_cancellationpoint: {
1885 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1886 // global_tid, kmp_int32 cncl_kind)
1887 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1888 llvm::FunctionType *FnTy =
1889 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1890 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1891 break;
1892 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001893 case OMPRTL__kmpc_cancel: {
1894 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1895 // kmp_int32 cncl_kind)
1896 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1897 llvm::FunctionType *FnTy =
1898 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1899 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1900 break;
1901 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001902 case OMPRTL__kmpc_push_num_teams: {
1903 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1904 // kmp_int32 num_teams, kmp_int32 num_threads)
1905 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1906 CGM.Int32Ty};
1907 llvm::FunctionType *FnTy =
1908 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1909 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1910 break;
1911 }
1912 case OMPRTL__kmpc_fork_teams: {
1913 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1914 // microtask, ...);
1915 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1916 getKmpc_MicroPointerTy()};
1917 llvm::FunctionType *FnTy =
1918 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1919 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1920 break;
1921 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001922 case OMPRTL__kmpc_taskloop: {
1923 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1924 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1925 // sched, kmp_uint64 grainsize, void *task_dup);
1926 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1927 CGM.IntTy,
1928 CGM.VoidPtrTy,
1929 CGM.IntTy,
1930 CGM.Int64Ty->getPointerTo(),
1931 CGM.Int64Ty->getPointerTo(),
1932 CGM.Int64Ty,
1933 CGM.IntTy,
1934 CGM.IntTy,
1935 CGM.Int64Ty,
1936 CGM.VoidPtrTy};
1937 llvm::FunctionType *FnTy =
1938 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1939 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1940 break;
1941 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001942 case OMPRTL__kmpc_doacross_init: {
1943 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1944 // num_dims, struct kmp_dim *dims);
1945 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1946 CGM.Int32Ty,
1947 CGM.Int32Ty,
1948 CGM.VoidPtrTy};
1949 llvm::FunctionType *FnTy =
1950 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1952 break;
1953 }
1954 case OMPRTL__kmpc_doacross_fini: {
1955 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1956 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1957 llvm::FunctionType *FnTy =
1958 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1959 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1960 break;
1961 }
1962 case OMPRTL__kmpc_doacross_post: {
1963 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1964 // *vec);
1965 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1966 CGM.Int64Ty->getPointerTo()};
1967 llvm::FunctionType *FnTy =
1968 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1969 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1970 break;
1971 }
1972 case OMPRTL__kmpc_doacross_wait: {
1973 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1974 // *vec);
1975 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1976 CGM.Int64Ty->getPointerTo()};
1977 llvm::FunctionType *FnTy =
1978 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1979 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1980 break;
1981 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001982 case OMPRTL__kmpc_task_reduction_init: {
1983 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1984 // *data);
1985 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
1986 llvm::FunctionType *FnTy =
1987 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1988 RTLFn =
1989 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
1990 break;
1991 }
1992 case OMPRTL__kmpc_task_reduction_get_th_data: {
1993 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
1994 // *d);
1995 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
1996 llvm::FunctionType *FnTy =
1997 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1998 RTLFn = CGM.CreateRuntimeFunction(
1999 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2000 break;
2001 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002002 case OMPRTL__tgt_target: {
2003 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
2004 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
2005 // *arg_types);
2006 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2007 CGM.VoidPtrTy,
2008 CGM.Int32Ty,
2009 CGM.VoidPtrPtrTy,
2010 CGM.VoidPtrPtrTy,
2011 CGM.SizeTy->getPointerTo(),
2012 CGM.Int32Ty->getPointerTo()};
2013 llvm::FunctionType *FnTy =
2014 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2015 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2016 break;
2017 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002018 case OMPRTL__tgt_target_teams: {
2019 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2020 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2021 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2022 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2023 CGM.VoidPtrTy,
2024 CGM.Int32Ty,
2025 CGM.VoidPtrPtrTy,
2026 CGM.VoidPtrPtrTy,
2027 CGM.SizeTy->getPointerTo(),
2028 CGM.Int32Ty->getPointerTo(),
2029 CGM.Int32Ty,
2030 CGM.Int32Ty};
2031 llvm::FunctionType *FnTy =
2032 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2033 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2034 break;
2035 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002036 case OMPRTL__tgt_register_lib: {
2037 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2038 QualType ParamTy =
2039 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2040 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2041 llvm::FunctionType *FnTy =
2042 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2043 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2044 break;
2045 }
2046 case OMPRTL__tgt_unregister_lib: {
2047 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2048 QualType ParamTy =
2049 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2050 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2051 llvm::FunctionType *FnTy =
2052 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2053 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2054 break;
2055 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002056 case OMPRTL__tgt_target_data_begin: {
2057 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2058 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2059 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2060 CGM.Int32Ty,
2061 CGM.VoidPtrPtrTy,
2062 CGM.VoidPtrPtrTy,
2063 CGM.SizeTy->getPointerTo(),
2064 CGM.Int32Ty->getPointerTo()};
2065 llvm::FunctionType *FnTy =
2066 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2067 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2068 break;
2069 }
2070 case OMPRTL__tgt_target_data_end: {
2071 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2072 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2073 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2074 CGM.Int32Ty,
2075 CGM.VoidPtrPtrTy,
2076 CGM.VoidPtrPtrTy,
2077 CGM.SizeTy->getPointerTo(),
2078 CGM.Int32Ty->getPointerTo()};
2079 llvm::FunctionType *FnTy =
2080 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2081 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2082 break;
2083 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002084 case OMPRTL__tgt_target_data_update: {
2085 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2086 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2087 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2088 CGM.Int32Ty,
2089 CGM.VoidPtrPtrTy,
2090 CGM.VoidPtrPtrTy,
2091 CGM.SizeTy->getPointerTo(),
2092 CGM.Int32Ty->getPointerTo()};
2093 llvm::FunctionType *FnTy =
2094 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2095 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2096 break;
2097 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002098 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002099 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002100 return RTLFn;
2101}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002102
Alexander Musman21212e42015-03-13 10:38:23 +00002103llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2104 bool IVSigned) {
2105 assert((IVSize == 32 || IVSize == 64) &&
2106 "IV size is not compatible with the omp runtime");
2107 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2108 : "__kmpc_for_static_init_4u")
2109 : (IVSigned ? "__kmpc_for_static_init_8"
2110 : "__kmpc_for_static_init_8u");
2111 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2112 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2113 llvm::Type *TypeParams[] = {
2114 getIdentTyPointerTy(), // loc
2115 CGM.Int32Ty, // tid
2116 CGM.Int32Ty, // schedtype
2117 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2118 PtrTy, // p_lower
2119 PtrTy, // p_upper
2120 PtrTy, // p_stride
2121 ITy, // incr
2122 ITy // chunk
2123 };
2124 llvm::FunctionType *FnTy =
2125 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2126 return CGM.CreateRuntimeFunction(FnTy, Name);
2127}
2128
Alexander Musman92bdaab2015-03-12 13:37:50 +00002129llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2130 bool IVSigned) {
2131 assert((IVSize == 32 || IVSize == 64) &&
2132 "IV size is not compatible with the omp runtime");
2133 auto Name =
2134 IVSize == 32
2135 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2136 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2137 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2138 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2139 CGM.Int32Ty, // tid
2140 CGM.Int32Ty, // schedtype
2141 ITy, // lower
2142 ITy, // upper
2143 ITy, // stride
2144 ITy // chunk
2145 };
2146 llvm::FunctionType *FnTy =
2147 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2148 return CGM.CreateRuntimeFunction(FnTy, Name);
2149}
2150
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002151llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2152 bool IVSigned) {
2153 assert((IVSize == 32 || IVSize == 64) &&
2154 "IV size is not compatible with the omp runtime");
2155 auto Name =
2156 IVSize == 32
2157 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2158 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2159 llvm::Type *TypeParams[] = {
2160 getIdentTyPointerTy(), // loc
2161 CGM.Int32Ty, // tid
2162 };
2163 llvm::FunctionType *FnTy =
2164 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2165 return CGM.CreateRuntimeFunction(FnTy, Name);
2166}
2167
Alexander Musman92bdaab2015-03-12 13:37:50 +00002168llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2169 bool IVSigned) {
2170 assert((IVSize == 32 || IVSize == 64) &&
2171 "IV size is not compatible with the omp runtime");
2172 auto Name =
2173 IVSize == 32
2174 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2175 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2176 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2177 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2178 llvm::Type *TypeParams[] = {
2179 getIdentTyPointerTy(), // loc
2180 CGM.Int32Ty, // tid
2181 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2182 PtrTy, // p_lower
2183 PtrTy, // p_upper
2184 PtrTy // p_stride
2185 };
2186 llvm::FunctionType *FnTy =
2187 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2188 return CGM.CreateRuntimeFunction(FnTy, Name);
2189}
2190
Alexey Bataev97720002014-11-11 04:05:39 +00002191llvm::Constant *
2192CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002193 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2194 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002195 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002196 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002197 Twine(CGM.getMangledName(VD)) + ".cache.");
2198}
2199
John McCall7f416cc2015-09-08 08:05:57 +00002200Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2201 const VarDecl *VD,
2202 Address VDAddr,
2203 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002204 if (CGM.getLangOpts().OpenMPUseTLS &&
2205 CGM.getContext().getTargetInfo().isTLSSupported())
2206 return VDAddr;
2207
John McCall7f416cc2015-09-08 08:05:57 +00002208 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002209 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002210 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2211 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002212 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2213 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002214 return Address(CGF.EmitRuntimeCall(
2215 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2216 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002217}
2218
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002219void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002220 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002221 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2222 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2223 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002224 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2225 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002226 OMPLoc);
2227 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2228 // to register constructor/destructor for variable.
2229 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002230 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2231 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002232 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002233 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002234 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002235}
2236
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002237llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002238 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002239 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002240 if (CGM.getLangOpts().OpenMPUseTLS &&
2241 CGM.getContext().getTargetInfo().isTLSSupported())
2242 return nullptr;
2243
Alexey Bataev97720002014-11-11 04:05:39 +00002244 VD = VD->getDefinition(CGM.getContext());
2245 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2246 ThreadPrivateWithDefinition.insert(VD);
2247 QualType ASTTy = VD->getType();
2248
2249 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2250 auto Init = VD->getAnyInitializer();
2251 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2252 // Generate function that re-emits the declaration's initializer into the
2253 // threadprivate copy of the variable VD
2254 CodeGenFunction CtorCGF(CGM);
2255 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002256 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2257 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002258 Args.push_back(&Dst);
2259
John McCallc56a8b32016-03-11 04:30:31 +00002260 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2261 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002262 auto FTy = CGM.getTypes().GetFunctionType(FI);
2263 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002264 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002265 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2266 Args, SourceLocation());
2267 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002268 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002269 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002270 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2271 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2272 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002273 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2274 /*IsInitializer=*/true);
2275 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002276 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002277 CGM.getContext().VoidPtrTy, Dst.getLocation());
2278 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2279 CtorCGF.FinishFunction();
2280 Ctor = Fn;
2281 }
2282 if (VD->getType().isDestructedType() != QualType::DK_none) {
2283 // Generate function that emits destructor call for the threadprivate copy
2284 // of the variable VD
2285 CodeGenFunction DtorCGF(CGM);
2286 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002287 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2288 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002289 Args.push_back(&Dst);
2290
John McCallc56a8b32016-03-11 04:30:31 +00002291 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2292 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002293 auto FTy = CGM.getTypes().GetFunctionType(FI);
2294 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002295 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002296 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002297 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2298 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002299 // Create a scope with an artificial location for the body of this function.
2300 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002301 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2302 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002303 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2304 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002305 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2306 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2307 DtorCGF.FinishFunction();
2308 Dtor = Fn;
2309 }
2310 // Do not emit init function if it is not required.
2311 if (!Ctor && !Dtor)
2312 return nullptr;
2313
2314 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2315 auto CopyCtorTy =
2316 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2317 /*isVarArg=*/false)->getPointerTo();
2318 // Copying constructor for the threadprivate variable.
2319 // Must be NULL - reserved by runtime, but currently it requires that this
2320 // parameter is always NULL. Otherwise it fires assertion.
2321 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2322 if (Ctor == nullptr) {
2323 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2324 /*isVarArg=*/false)->getPointerTo();
2325 Ctor = llvm::Constant::getNullValue(CtorTy);
2326 }
2327 if (Dtor == nullptr) {
2328 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2329 /*isVarArg=*/false)->getPointerTo();
2330 Dtor = llvm::Constant::getNullValue(DtorTy);
2331 }
2332 if (!CGF) {
2333 auto InitFunctionTy =
2334 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2335 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002336 InitFunctionTy, ".__omp_threadprivate_init_.",
2337 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002338 CodeGenFunction InitCGF(CGM);
2339 FunctionArgList ArgList;
2340 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2341 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2342 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002343 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002344 InitCGF.FinishFunction();
2345 return InitFunction;
2346 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002347 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002348 }
2349 return nullptr;
2350}
2351
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002352Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2353 QualType VarType,
2354 StringRef Name) {
2355 llvm::Twine VarName(Name, ".artificial.");
2356 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2357 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2358 llvm::Value *Args[] = {
2359 emitUpdateLocation(CGF, SourceLocation()),
2360 getThreadID(CGF, SourceLocation()),
2361 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2362 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2363 /*IsSigned=*/false),
2364 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2365 return Address(
2366 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2367 CGF.EmitRuntimeCall(
2368 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2369 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2370 CGM.getPointerAlign());
2371}
2372
Alexey Bataev1d677132015-04-22 13:57:31 +00002373/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2374/// function. Here is the logic:
2375/// if (Cond) {
2376/// ThenGen();
2377/// } else {
2378/// ElseGen();
2379/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002380void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2381 const RegionCodeGenTy &ThenGen,
2382 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002383 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2384
2385 // If the condition constant folds and can be elided, try to avoid emitting
2386 // the condition and the dead arm of the if/else.
2387 bool CondConstant;
2388 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002389 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002390 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002391 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002392 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002393 return;
2394 }
2395
2396 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2397 // emit the conditional branch.
2398 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2399 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2400 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2401 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2402
2403 // Emit the 'then' code.
2404 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002405 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002406 CGF.EmitBranch(ContBlock);
2407 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002408 // There is no need to emit line number for unconditional branch.
2409 (void)ApplyDebugLocation::CreateEmpty(CGF);
2410 CGF.EmitBlock(ElseBlock);
2411 ElseGen(CGF);
2412 // There is no need to emit line number for unconditional branch.
2413 (void)ApplyDebugLocation::CreateEmpty(CGF);
2414 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002415 // Emit the continuation block for code after the if.
2416 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002417}
2418
Alexey Bataev1d677132015-04-22 13:57:31 +00002419void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2420 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002421 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002422 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002423 if (!CGF.HaveInsertPoint())
2424 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002425 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002426 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2427 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002428 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002429 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002430 llvm::Value *Args[] = {
2431 RTLoc,
2432 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002433 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002434 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2435 RealArgs.append(std::begin(Args), std::end(Args));
2436 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2437
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002438 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002439 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2440 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002441 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2442 PrePostActionTy &) {
2443 auto &RT = CGF.CGM.getOpenMPRuntime();
2444 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002445 // Build calls:
2446 // __kmpc_serialized_parallel(&Loc, GTid);
2447 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002448 CGF.EmitRuntimeCall(
2449 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002450
Alexey Bataev1d677132015-04-22 13:57:31 +00002451 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002452 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002453 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002454 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2455 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002456 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002457 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2458 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2459 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2460 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002461 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002462
Alexey Bataev1d677132015-04-22 13:57:31 +00002463 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002464 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002465 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002466 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2467 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002468 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002469 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002470 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002471 else {
2472 RegionCodeGenTy ThenRCG(ThenGen);
2473 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002474 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002475}
2476
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002477// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002478// thread-ID variable (it is passed in a first argument of the outlined function
2479// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2480// regular serial code region, get thread ID by calling kmp_int32
2481// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2482// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002483Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2484 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002485 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002486 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002487 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002488 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002489
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002490 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002491 auto Int32Ty =
2492 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2493 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2494 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002495 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002496
2497 return ThreadIDTemp;
2498}
2499
Alexey Bataev97720002014-11-11 04:05:39 +00002500llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002501CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002502 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002503 SmallString<256> Buffer;
2504 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002505 Out << Name;
2506 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002507 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2508 if (Elem.second) {
2509 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002510 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002511 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002512 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002513
David Blaikie13156b62014-11-19 03:06:06 +00002514 return Elem.second = new llvm::GlobalVariable(
2515 CGM.getModule(), Ty, /*IsConstant*/ false,
2516 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2517 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002518}
2519
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002520llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002521 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002522 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002523}
2524
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002525namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002526/// Common pre(post)-action for different OpenMP constructs.
2527class CommonActionTy final : public PrePostActionTy {
2528 llvm::Value *EnterCallee;
2529 ArrayRef<llvm::Value *> EnterArgs;
2530 llvm::Value *ExitCallee;
2531 ArrayRef<llvm::Value *> ExitArgs;
2532 bool Conditional;
2533 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002534
2535public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002536 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2537 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2538 bool Conditional = false)
2539 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2540 ExitArgs(ExitArgs), Conditional(Conditional) {}
2541 void Enter(CodeGenFunction &CGF) override {
2542 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2543 if (Conditional) {
2544 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2545 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2546 ContBlock = CGF.createBasicBlock("omp_if.end");
2547 // Generate the branch (If-stmt)
2548 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2549 CGF.EmitBlock(ThenBlock);
2550 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002551 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002552 void Done(CodeGenFunction &CGF) {
2553 // Emit the rest of blocks/branches
2554 CGF.EmitBranch(ContBlock);
2555 CGF.EmitBlock(ContBlock, true);
2556 }
2557 void Exit(CodeGenFunction &CGF) override {
2558 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002559 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002560};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002561} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002562
2563void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2564 StringRef CriticalName,
2565 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002566 SourceLocation Loc, const Expr *Hint) {
2567 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002568 // CriticalOpGen();
2569 // __kmpc_end_critical(ident_t *, gtid, Lock);
2570 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002571 if (!CGF.HaveInsertPoint())
2572 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002573 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2574 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002575 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2576 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002577 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002578 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2579 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2580 }
2581 CommonActionTy Action(
2582 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2583 : OMPRTL__kmpc_critical),
2584 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2585 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002586 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002587}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002588
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002589void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002590 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002591 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002592 if (!CGF.HaveInsertPoint())
2593 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002594 // if(__kmpc_master(ident_t *, gtid)) {
2595 // MasterOpGen();
2596 // __kmpc_end_master(ident_t *, gtid);
2597 // }
2598 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002599 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002600 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2601 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2602 /*Conditional=*/true);
2603 MasterOpGen.setAction(Action);
2604 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2605 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002606}
2607
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002608void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2609 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002610 if (!CGF.HaveInsertPoint())
2611 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002612 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2613 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002614 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002615 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002616 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002617 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2618 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002619}
2620
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002621void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2622 const RegionCodeGenTy &TaskgroupOpGen,
2623 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002624 if (!CGF.HaveInsertPoint())
2625 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002626 // __kmpc_taskgroup(ident_t *, gtid);
2627 // TaskgroupOpGen();
2628 // __kmpc_end_taskgroup(ident_t *, gtid);
2629 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002630 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2631 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2632 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2633 Args);
2634 TaskgroupOpGen.setAction(Action);
2635 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002636}
2637
John McCall7f416cc2015-09-08 08:05:57 +00002638/// Given an array of pointers to variables, project the address of a
2639/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002640static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2641 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002642 // Pull out the pointer to the variable.
2643 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002644 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002645 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2646
2647 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002648 Addr = CGF.Builder.CreateElementBitCast(
2649 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002650 return Addr;
2651}
2652
Alexey Bataeva63048e2015-03-23 06:18:07 +00002653static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002654 CodeGenModule &CGM, llvm::Type *ArgsType,
2655 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2656 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002657 auto &C = CGM.getContext();
2658 // void copy_func(void *LHSArg, void *RHSArg);
2659 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002660 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2661 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002662 Args.push_back(&LHSArg);
2663 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002664 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002665 auto *Fn = llvm::Function::Create(
2666 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2667 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002668 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002669 CodeGenFunction CGF(CGM);
2670 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002671 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002672 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002673 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2674 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2675 ArgsType), CGF.getPointerAlign());
2676 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2677 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2678 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002679 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2680 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2681 // ...
2682 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002683 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002684 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2685 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2686
2687 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2688 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2689
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002690 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2691 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002692 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002693 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002694 CGF.FinishFunction();
2695 return Fn;
2696}
2697
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002698void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002699 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002700 SourceLocation Loc,
2701 ArrayRef<const Expr *> CopyprivateVars,
2702 ArrayRef<const Expr *> SrcExprs,
2703 ArrayRef<const Expr *> DstExprs,
2704 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002705 if (!CGF.HaveInsertPoint())
2706 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002707 assert(CopyprivateVars.size() == SrcExprs.size() &&
2708 CopyprivateVars.size() == DstExprs.size() &&
2709 CopyprivateVars.size() == AssignmentOps.size());
2710 auto &C = CGM.getContext();
2711 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002712 // if(__kmpc_single(ident_t *, gtid)) {
2713 // SingleOpGen();
2714 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002715 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002716 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002717 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2718 // <copy_func>, did_it);
2719
John McCall7f416cc2015-09-08 08:05:57 +00002720 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002721 if (!CopyprivateVars.empty()) {
2722 // int32 did_it = 0;
2723 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2724 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002725 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002726 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002727 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002728 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002729 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2730 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2731 /*Conditional=*/true);
2732 SingleOpGen.setAction(Action);
2733 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2734 if (DidIt.isValid()) {
2735 // did_it = 1;
2736 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2737 }
2738 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002739 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2740 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002741 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002742 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2743 auto CopyprivateArrayTy =
2744 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2745 /*IndexTypeQuals=*/0);
2746 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002747 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002748 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2749 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002750 Address Elem = CGF.Builder.CreateConstArrayGEP(
2751 CopyprivateList, I, CGF.getPointerSize());
2752 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002753 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002754 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2755 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002756 }
2757 // Build function that copies private values from single region to all other
2758 // threads in the corresponding parallel region.
2759 auto *CpyFn = emitCopyprivateCopyFunction(
2760 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002761 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002762 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002763 Address CL =
2764 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2765 CGF.VoidPtrTy);
2766 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002767 llvm::Value *Args[] = {
2768 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2769 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002770 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002771 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002772 CpyFn, // void (*) (void *, void *) <copy_func>
2773 DidItVal // i32 did_it
2774 };
2775 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2776 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002777}
2778
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002779void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2780 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002781 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002782 if (!CGF.HaveInsertPoint())
2783 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002784 // __kmpc_ordered(ident_t *, gtid);
2785 // OrderedOpGen();
2786 // __kmpc_end_ordered(ident_t *, gtid);
2787 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002788 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002789 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002790 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2791 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2792 Args);
2793 OrderedOpGen.setAction(Action);
2794 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2795 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002796 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002797 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002798}
2799
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002800void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002801 OpenMPDirectiveKind Kind, bool EmitChecks,
2802 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002803 if (!CGF.HaveInsertPoint())
2804 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002805 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002806 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002807 unsigned Flags;
2808 if (Kind == OMPD_for)
2809 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2810 else if (Kind == OMPD_sections)
2811 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2812 else if (Kind == OMPD_single)
2813 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2814 else if (Kind == OMPD_barrier)
2815 Flags = OMP_IDENT_BARRIER_EXPL;
2816 else
2817 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002818 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2819 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002820 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2821 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002822 if (auto *OMPRegionInfo =
2823 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002824 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002825 auto *Result = CGF.EmitRuntimeCall(
2826 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002827 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002828 // if (__kmpc_cancel_barrier()) {
2829 // exit from construct;
2830 // }
2831 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2832 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2833 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2834 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2835 CGF.EmitBlock(ExitBB);
2836 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002837 auto CancelDestination =
2838 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002839 CGF.EmitBranchThroughCleanup(CancelDestination);
2840 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2841 }
2842 return;
2843 }
2844 }
2845 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002846}
2847
Alexander Musmanc6388682014-12-15 07:07:06 +00002848/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2849static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002850 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002851 switch (ScheduleKind) {
2852 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002853 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2854 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002855 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002856 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002857 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002858 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002859 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002860 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2861 case OMPC_SCHEDULE_auto:
2862 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002863 case OMPC_SCHEDULE_unknown:
2864 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002865 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002866 }
2867 llvm_unreachable("Unexpected runtime schedule");
2868}
2869
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002870/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2871static OpenMPSchedType
2872getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2873 // only static is allowed for dist_schedule
2874 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2875}
2876
Alexander Musmanc6388682014-12-15 07:07:06 +00002877bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2878 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002879 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002880 return Schedule == OMP_sch_static;
2881}
2882
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002883bool CGOpenMPRuntime::isStaticNonchunked(
2884 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2885 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2886 return Schedule == OMP_dist_sch_static;
2887}
2888
2889
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002890bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002891 auto Schedule =
2892 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002893 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2894 return Schedule != OMP_sch_static;
2895}
2896
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002897static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2898 OpenMPScheduleClauseModifier M1,
2899 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002900 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002901 switch (M1) {
2902 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002903 Modifier = OMP_sch_modifier_monotonic;
2904 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002905 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002906 Modifier = OMP_sch_modifier_nonmonotonic;
2907 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002908 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002909 if (Schedule == OMP_sch_static_chunked)
2910 Schedule = OMP_sch_static_balanced_chunked;
2911 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002912 case OMPC_SCHEDULE_MODIFIER_last:
2913 case OMPC_SCHEDULE_MODIFIER_unknown:
2914 break;
2915 }
2916 switch (M2) {
2917 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002918 Modifier = OMP_sch_modifier_monotonic;
2919 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002920 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002921 Modifier = OMP_sch_modifier_nonmonotonic;
2922 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002923 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002924 if (Schedule == OMP_sch_static_chunked)
2925 Schedule = OMP_sch_static_balanced_chunked;
2926 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002927 case OMPC_SCHEDULE_MODIFIER_last:
2928 case OMPC_SCHEDULE_MODIFIER_unknown:
2929 break;
2930 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002931 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002932}
2933
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002934void CGOpenMPRuntime::emitForDispatchInit(
2935 CodeGenFunction &CGF, SourceLocation Loc,
2936 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2937 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002938 if (!CGF.HaveInsertPoint())
2939 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002940 OpenMPSchedType Schedule = getRuntimeSchedule(
2941 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002942 assert(Ordered ||
2943 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002944 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2945 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002946 // Call __kmpc_dispatch_init(
2947 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2948 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2949 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002950
John McCall7f416cc2015-09-08 08:05:57 +00002951 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002952 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2953 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002954 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002955 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2956 CGF.Builder.getInt32(addMonoNonMonoModifier(
2957 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002958 DispatchValues.LB, // Lower
2959 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002960 CGF.Builder.getIntN(IVSize, 1), // Stride
2961 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002962 };
2963 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2964}
2965
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002966static void emitForStaticInitCall(
2967 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2968 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2969 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002970 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002971 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002972 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002973
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002974 assert(!Values.Ordered);
2975 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2976 Schedule == OMP_sch_static_balanced_chunked ||
2977 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2978 Schedule == OMP_dist_sch_static ||
2979 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002980
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002981 // Call __kmpc_for_static_init(
2982 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2983 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2984 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2985 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2986 llvm::Value *Chunk = Values.Chunk;
2987 if (Chunk == nullptr) {
2988 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2989 Schedule == OMP_dist_sch_static) &&
2990 "expected static non-chunked schedule");
2991 // If the Chunk was not specified in the clause - use default value 1.
2992 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
2993 } else {
2994 assert((Schedule == OMP_sch_static_chunked ||
2995 Schedule == OMP_sch_static_balanced_chunked ||
2996 Schedule == OMP_ord_static_chunked ||
2997 Schedule == OMP_dist_sch_static_chunked) &&
2998 "expected static chunked schedule");
2999 }
3000 llvm::Value *Args[] = {
3001 UpdateLocation,
3002 ThreadId,
3003 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3004 M2)), // Schedule type
3005 Values.IL.getPointer(), // &isLastIter
3006 Values.LB.getPointer(), // &LB
3007 Values.UB.getPointer(), // &UB
3008 Values.ST.getPointer(), // &Stride
3009 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3010 Chunk // Chunk
3011 };
3012 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003013}
3014
John McCall7f416cc2015-09-08 08:05:57 +00003015void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3016 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003017 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003018 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003019 const StaticRTInput &Values) {
3020 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3021 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3022 assert(isOpenMPWorksharingDirective(DKind) &&
3023 "Expected loop-based or sections-based directive.");
3024 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3025 isOpenMPLoopDirective(DKind)
3026 ? OMP_IDENT_WORK_LOOP
3027 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003028 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003029 auto *StaticInitFunction =
3030 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003031 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003032 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003033}
John McCall7f416cc2015-09-08 08:05:57 +00003034
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003035void CGOpenMPRuntime::emitDistributeStaticInit(
3036 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003037 OpenMPDistScheduleClauseKind SchedKind,
3038 const CGOpenMPRuntime::StaticRTInput &Values) {
3039 OpenMPSchedType ScheduleNum =
3040 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3041 auto *UpdatedLocation =
3042 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003043 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003044 auto *StaticInitFunction =
3045 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003046 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3047 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003048 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003049}
3050
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003051void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
3052 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003053 if (!CGF.HaveInsertPoint())
3054 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003055 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003056 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003057 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3058 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003059}
3060
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003061void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3062 SourceLocation Loc,
3063 unsigned IVSize,
3064 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003065 if (!CGF.HaveInsertPoint())
3066 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003067 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003068 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003069 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3070}
3071
Alexander Musman92bdaab2015-03-12 13:37:50 +00003072llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3073 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003074 bool IVSigned, Address IL,
3075 Address LB, Address UB,
3076 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003077 // Call __kmpc_dispatch_next(
3078 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3079 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3080 // kmp_int[32|64] *p_stride);
3081 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003082 emitUpdateLocation(CGF, Loc),
3083 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003084 IL.getPointer(), // &isLastIter
3085 LB.getPointer(), // &Lower
3086 UB.getPointer(), // &Upper
3087 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003088 };
3089 llvm::Value *Call =
3090 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3091 return CGF.EmitScalarConversion(
3092 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003093 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003094}
3095
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003096void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3097 llvm::Value *NumThreads,
3098 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003099 if (!CGF.HaveInsertPoint())
3100 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003101 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3102 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003103 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003104 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003105 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3106 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003107}
3108
Alexey Bataev7f210c62015-06-18 13:40:03 +00003109void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3110 OpenMPProcBindClauseKind ProcBind,
3111 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003112 if (!CGF.HaveInsertPoint())
3113 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003114 // Constants for proc bind value accepted by the runtime.
3115 enum ProcBindTy {
3116 ProcBindFalse = 0,
3117 ProcBindTrue,
3118 ProcBindMaster,
3119 ProcBindClose,
3120 ProcBindSpread,
3121 ProcBindIntel,
3122 ProcBindDefault
3123 } RuntimeProcBind;
3124 switch (ProcBind) {
3125 case OMPC_PROC_BIND_master:
3126 RuntimeProcBind = ProcBindMaster;
3127 break;
3128 case OMPC_PROC_BIND_close:
3129 RuntimeProcBind = ProcBindClose;
3130 break;
3131 case OMPC_PROC_BIND_spread:
3132 RuntimeProcBind = ProcBindSpread;
3133 break;
3134 case OMPC_PROC_BIND_unknown:
3135 llvm_unreachable("Unsupported proc_bind value.");
3136 }
3137 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3138 llvm::Value *Args[] = {
3139 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3140 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3141 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3142}
3143
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003144void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3145 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003146 if (!CGF.HaveInsertPoint())
3147 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003148 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003149 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3150 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003151}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003152
Alexey Bataev62b63b12015-03-10 07:28:44 +00003153namespace {
3154/// \brief Indexes of fields for type kmp_task_t.
3155enum KmpTaskTFields {
3156 /// \brief List of shared variables.
3157 KmpTaskTShareds,
3158 /// \brief Task routine.
3159 KmpTaskTRoutine,
3160 /// \brief Partition id for the untied tasks.
3161 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003162 /// Function with call of destructors for private variables.
3163 Data1,
3164 /// Task priority.
3165 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003166 /// (Taskloops only) Lower bound.
3167 KmpTaskTLowerBound,
3168 /// (Taskloops only) Upper bound.
3169 KmpTaskTUpperBound,
3170 /// (Taskloops only) Stride.
3171 KmpTaskTStride,
3172 /// (Taskloops only) Is last iteration flag.
3173 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003174 /// (Taskloops only) Reduction data.
3175 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003176};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003177} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003178
Samuel Antaoee8fb302016-01-06 13:42:12 +00003179bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3180 // FIXME: Add other entries type when they become supported.
3181 return OffloadEntriesTargetRegion.empty();
3182}
3183
3184/// \brief Initialize target region entry.
3185void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3186 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3187 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003188 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003189 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3190 "only required for the device "
3191 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003192 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003193 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3194 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003195 ++OffloadingEntriesNum;
3196}
3197
3198void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3199 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3200 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003201 llvm::Constant *Addr, llvm::Constant *ID,
3202 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003203 // If we are emitting code for a target, the entry is already initialized,
3204 // only has to be registered.
3205 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003206 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003207 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003208 auto &Entry =
3209 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003210 assert(Entry.isValid() && "Entry not initialized!");
3211 Entry.setAddress(Addr);
3212 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003213 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003214 return;
3215 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003216 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003217 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003218 }
3219}
3220
3221bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003222 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3223 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003224 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3225 if (PerDevice == OffloadEntriesTargetRegion.end())
3226 return false;
3227 auto PerFile = PerDevice->second.find(FileID);
3228 if (PerFile == PerDevice->second.end())
3229 return false;
3230 auto PerParentName = PerFile->second.find(ParentName);
3231 if (PerParentName == PerFile->second.end())
3232 return false;
3233 auto PerLine = PerParentName->second.find(LineNum);
3234 if (PerLine == PerParentName->second.end())
3235 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003236 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003237 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003238 return false;
3239 return true;
3240}
3241
3242void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3243 const OffloadTargetRegionEntryInfoActTy &Action) {
3244 // Scan all target region entries and perform the provided action.
3245 for (auto &D : OffloadEntriesTargetRegion)
3246 for (auto &F : D.second)
3247 for (auto &P : F.second)
3248 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003249 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003250}
3251
3252/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3253/// \a Codegen. This is used to emit the two functions that register and
3254/// unregister the descriptor of the current compilation unit.
3255static llvm::Function *
3256createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3257 const RegionCodeGenTy &Codegen) {
3258 auto &C = CGM.getContext();
3259 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003260 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003261 Args.push_back(&DummyPtr);
3262
3263 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003264 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003265 auto FTy = CGM.getTypes().GetFunctionType(FI);
3266 auto *Fn =
3267 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3268 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3269 Codegen(CGF);
3270 CGF.FinishFunction();
3271 return Fn;
3272}
3273
3274llvm::Function *
3275CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3276
3277 // If we don't have entries or if we are emitting code for the device, we
3278 // don't need to do anything.
3279 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3280 return nullptr;
3281
3282 auto &M = CGM.getModule();
3283 auto &C = CGM.getContext();
3284
3285 // Get list of devices we care about
3286 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3287
3288 // We should be creating an offloading descriptor only if there are devices
3289 // specified.
3290 assert(!Devices.empty() && "No OpenMP offloading devices??");
3291
3292 // Create the external variables that will point to the begin and end of the
3293 // host entries section. These will be defined by the linker.
3294 auto *OffloadEntryTy =
3295 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3296 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3297 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003298 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003299 ".omp_offloading.entries_begin");
3300 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3301 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003302 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003303 ".omp_offloading.entries_end");
3304
3305 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003306 auto *DeviceImageTy = cast<llvm::StructType>(
3307 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003308 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003309 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003310
3311 for (unsigned i = 0; i < Devices.size(); ++i) {
3312 StringRef T = Devices[i].getTriple();
3313 auto *ImgBegin = new llvm::GlobalVariable(
3314 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003315 /*Initializer=*/nullptr,
3316 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003317 auto *ImgEnd = new llvm::GlobalVariable(
3318 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003319 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003320
John McCall6c9f1fdb2016-11-19 08:17:24 +00003321 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3322 Dev.add(ImgBegin);
3323 Dev.add(ImgEnd);
3324 Dev.add(HostEntriesBegin);
3325 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003326 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003327 }
3328
3329 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003330 llvm::GlobalVariable *DeviceImages =
3331 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3332 CGM.getPointerAlign(),
3333 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003334 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003335
3336 // This is a Zero array to be used in the creation of the constant expressions
3337 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3338 llvm::Constant::getNullValue(CGM.Int32Ty)};
3339
3340 // Create the target region descriptor.
3341 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3342 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003343 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003344 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3345 DescInit.addInt(CGM.Int32Ty, Devices.size());
3346 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3347 DeviceImages,
3348 Index));
3349 DescInit.add(HostEntriesBegin);
3350 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003351
John McCall6c9f1fdb2016-11-19 08:17:24 +00003352 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3353 CGM.getPointerAlign(),
3354 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003355
3356 // Emit code to register or unregister the descriptor at execution
3357 // startup or closing, respectively.
3358
3359 // Create a variable to drive the registration and unregistration of the
3360 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3361 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3362 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003363 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003364
3365 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003366 CGM, ".omp_offloading.descriptor_unreg",
3367 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003368 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3369 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003370 });
3371 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003372 CGM, ".omp_offloading.descriptor_reg",
3373 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003374 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3375 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003376 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3377 });
George Rokos29d0f002017-05-27 03:03:13 +00003378 if (CGM.supportsCOMDAT()) {
3379 // It is sufficient to call registration function only once, so create a
3380 // COMDAT group for registration/unregistration functions and associated
3381 // data. That would reduce startup time and code size. Registration
3382 // function serves as a COMDAT group key.
3383 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3384 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3385 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3386 RegFn->setComdat(ComdatKey);
3387 UnRegFn->setComdat(ComdatKey);
3388 DeviceImages->setComdat(ComdatKey);
3389 Desc->setComdat(ComdatKey);
3390 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003391 return RegFn;
3392}
3393
Samuel Antao2de62b02016-02-13 23:35:10 +00003394void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003395 llvm::Constant *Addr, uint64_t Size,
3396 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003397 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003398 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3399 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3400 llvm::LLVMContext &C = CGM.getModule().getContext();
3401 llvm::Module &M = CGM.getModule();
3402
3403 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003404 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003405
3406 // Create constant string with the name.
3407 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3408
3409 llvm::GlobalVariable *Str =
3410 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3411 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3412 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003413 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003414 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3415
John McCall6c9f1fdb2016-11-19 08:17:24 +00003416 // We can't have any padding between symbols, so we need to have 1-byte
3417 // alignment.
3418 auto Align = CharUnits::fromQuantity(1);
3419
Samuel Antaoee8fb302016-01-06 13:42:12 +00003420 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003421 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003422 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3423 EntryInit.add(AddrPtr);
3424 EntryInit.add(StrPtr);
3425 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003426 EntryInit.addInt(CGM.Int32Ty, Flags);
3427 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003428 llvm::GlobalVariable *Entry =
3429 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3430 Align,
3431 /*constant*/ true,
3432 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003433
3434 // The entry has to be created in the section the linker expects it to be.
3435 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003436}
3437
3438void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3439 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003440 // can easily figure out what to emit. The produced metadata looks like
3441 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003442 //
3443 // !omp_offload.info = !{!1, ...}
3444 //
3445 // Right now we only generate metadata for function that contain target
3446 // regions.
3447
3448 // If we do not have entries, we dont need to do anything.
3449 if (OffloadEntriesInfoManager.empty())
3450 return;
3451
3452 llvm::Module &M = CGM.getModule();
3453 llvm::LLVMContext &C = M.getContext();
3454 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3455 OrderedEntries(OffloadEntriesInfoManager.size());
3456
3457 // Create the offloading info metadata node.
3458 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3459
Simon Pilgrim2c518802017-03-30 14:13:19 +00003460 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003461 auto getMDInt = [&](unsigned v) {
3462 return llvm::ConstantAsMetadata::get(
3463 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3464 };
3465
3466 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3467
3468 // Create function that emits metadata for each target region entry;
3469 auto &&TargetRegionMetadataEmitter = [&](
3470 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003471 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3472 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3473 // Generate metadata for target regions. Each entry of this metadata
3474 // contains:
3475 // - Entry 0 -> Kind of this type of metadata (0).
3476 // - Entry 1 -> Device ID of the file where the entry was identified.
3477 // - Entry 2 -> File ID of the file where the entry was identified.
3478 // - Entry 3 -> Mangled name of the function where the entry was identified.
3479 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003480 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003481 // The first element of the metadata node is the kind.
3482 Ops.push_back(getMDInt(E.getKind()));
3483 Ops.push_back(getMDInt(DeviceID));
3484 Ops.push_back(getMDInt(FileID));
3485 Ops.push_back(getMDString(ParentName));
3486 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003487 Ops.push_back(getMDInt(E.getOrder()));
3488
3489 // Save this entry in the right position of the ordered entries array.
3490 OrderedEntries[E.getOrder()] = &E;
3491
3492 // Add metadata to the named metadata node.
3493 MD->addOperand(llvm::MDNode::get(C, Ops));
3494 };
3495
3496 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3497 TargetRegionMetadataEmitter);
3498
3499 for (auto *E : OrderedEntries) {
3500 assert(E && "All ordered entries must exist!");
3501 if (auto *CE =
3502 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3503 E)) {
3504 assert(CE->getID() && CE->getAddress() &&
3505 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003506 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003507 } else
3508 llvm_unreachable("Unsupported entry kind.");
3509 }
3510}
3511
3512/// \brief Loads all the offload entries information from the host IR
3513/// metadata.
3514void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3515 // If we are in target mode, load the metadata from the host IR. This code has
3516 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3517
3518 if (!CGM.getLangOpts().OpenMPIsDevice)
3519 return;
3520
3521 if (CGM.getLangOpts().OMPHostIRFile.empty())
3522 return;
3523
3524 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3525 if (Buf.getError())
3526 return;
3527
3528 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003529 auto ME = expectedToErrorOrAndEmitErrors(
3530 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003531
3532 if (ME.getError())
3533 return;
3534
3535 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3536 if (!MD)
3537 return;
3538
3539 for (auto I : MD->operands()) {
3540 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3541
3542 auto getMDInt = [&](unsigned Idx) {
3543 llvm::ConstantAsMetadata *V =
3544 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3545 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3546 };
3547
3548 auto getMDString = [&](unsigned Idx) {
3549 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3550 return V->getString();
3551 };
3552
3553 switch (getMDInt(0)) {
3554 default:
3555 llvm_unreachable("Unexpected metadata!");
3556 break;
3557 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3558 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3559 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3560 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3561 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003562 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003563 break;
3564 }
3565 }
3566}
3567
Alexey Bataev62b63b12015-03-10 07:28:44 +00003568void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3569 if (!KmpRoutineEntryPtrTy) {
3570 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3571 auto &C = CGM.getContext();
3572 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3573 FunctionProtoType::ExtProtoInfo EPI;
3574 KmpRoutineEntryPtrQTy = C.getPointerType(
3575 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3576 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3577 }
3578}
3579
Alexey Bataevc71a4092015-09-11 10:29:41 +00003580static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3581 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003582 auto *Field = FieldDecl::Create(
3583 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3584 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3585 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3586 Field->setAccess(AS_public);
3587 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003588 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003589}
3590
Samuel Antaoee8fb302016-01-06 13:42:12 +00003591QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3592
3593 // Make sure the type of the entry is already created. This is the type we
3594 // have to create:
3595 // struct __tgt_offload_entry{
3596 // void *addr; // Pointer to the offload entry info.
3597 // // (function or global)
3598 // char *name; // Name of the function or global.
3599 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003600 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3601 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003602 // };
3603 if (TgtOffloadEntryQTy.isNull()) {
3604 ASTContext &C = CGM.getContext();
3605 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3606 RD->startDefinition();
3607 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3608 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3609 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003610 addFieldToRecordDecl(
3611 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3612 addFieldToRecordDecl(
3613 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003614 RD->completeDefinition();
3615 TgtOffloadEntryQTy = C.getRecordType(RD);
3616 }
3617 return TgtOffloadEntryQTy;
3618}
3619
3620QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3621 // These are the types we need to build:
3622 // struct __tgt_device_image{
3623 // void *ImageStart; // Pointer to the target code start.
3624 // void *ImageEnd; // Pointer to the target code end.
3625 // // We also add the host entries to the device image, as it may be useful
3626 // // for the target runtime to have access to that information.
3627 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3628 // // the entries.
3629 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3630 // // entries (non inclusive).
3631 // };
3632 if (TgtDeviceImageQTy.isNull()) {
3633 ASTContext &C = CGM.getContext();
3634 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3635 RD->startDefinition();
3636 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3637 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3638 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3639 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3640 RD->completeDefinition();
3641 TgtDeviceImageQTy = C.getRecordType(RD);
3642 }
3643 return TgtDeviceImageQTy;
3644}
3645
3646QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3647 // struct __tgt_bin_desc{
3648 // int32_t NumDevices; // Number of devices supported.
3649 // __tgt_device_image *DeviceImages; // Arrays of device images
3650 // // (one per device).
3651 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3652 // // entries.
3653 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3654 // // entries (non inclusive).
3655 // };
3656 if (TgtBinaryDescriptorQTy.isNull()) {
3657 ASTContext &C = CGM.getContext();
3658 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3659 RD->startDefinition();
3660 addFieldToRecordDecl(
3661 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3662 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3663 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3664 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3665 RD->completeDefinition();
3666 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3667 }
3668 return TgtBinaryDescriptorQTy;
3669}
3670
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003671namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003672struct PrivateHelpersTy {
3673 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3674 const VarDecl *PrivateElemInit)
3675 : Original(Original), PrivateCopy(PrivateCopy),
3676 PrivateElemInit(PrivateElemInit) {}
3677 const VarDecl *Original;
3678 const VarDecl *PrivateCopy;
3679 const VarDecl *PrivateElemInit;
3680};
3681typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003682} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003683
Alexey Bataev9e034042015-05-05 04:05:12 +00003684static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003685createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003686 if (!Privates.empty()) {
3687 auto &C = CGM.getContext();
3688 // Build struct .kmp_privates_t. {
3689 // /* private vars */
3690 // };
3691 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3692 RD->startDefinition();
3693 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003694 auto *VD = Pair.second.Original;
3695 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003696 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003697 auto *FD = addFieldToRecordDecl(C, RD, Type);
3698 if (VD->hasAttrs()) {
3699 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3700 E(VD->getAttrs().end());
3701 I != E; ++I)
3702 FD->addAttr(*I);
3703 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003704 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003705 RD->completeDefinition();
3706 return RD;
3707 }
3708 return nullptr;
3709}
3710
Alexey Bataev9e034042015-05-05 04:05:12 +00003711static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003712createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3713 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003714 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003715 auto &C = CGM.getContext();
3716 // Build struct kmp_task_t {
3717 // void * shareds;
3718 // kmp_routine_entry_t routine;
3719 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003720 // kmp_cmplrdata_t data1;
3721 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003722 // For taskloops additional fields:
3723 // kmp_uint64 lb;
3724 // kmp_uint64 ub;
3725 // kmp_int64 st;
3726 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003727 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003728 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003729 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3730 UD->startDefinition();
3731 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3732 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3733 UD->completeDefinition();
3734 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003735 auto *RD = C.buildImplicitRecord("kmp_task_t");
3736 RD->startDefinition();
3737 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3738 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3739 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003740 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3741 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003742 if (isOpenMPTaskLoopDirective(Kind)) {
3743 QualType KmpUInt64Ty =
3744 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3745 QualType KmpInt64Ty =
3746 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3747 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3748 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3749 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3750 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003751 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003752 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003753 RD->completeDefinition();
3754 return RD;
3755}
3756
3757static RecordDecl *
3758createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003759 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003760 auto &C = CGM.getContext();
3761 // Build struct kmp_task_t_with_privates {
3762 // kmp_task_t task_data;
3763 // .kmp_privates_t. privates;
3764 // };
3765 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3766 RD->startDefinition();
3767 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003768 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3769 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3770 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003771 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003772 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003773}
3774
3775/// \brief Emit a proxy function which accepts kmp_task_t as the second
3776/// argument.
3777/// \code
3778/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003779/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003780/// For taskloops:
3781/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003782/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003783/// return 0;
3784/// }
3785/// \endcode
3786static llvm::Value *
3787emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003788 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3789 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003790 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003791 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3792 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003793 auto &C = CGM.getContext();
3794 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003795 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3796 ImplicitParamDecl::Other);
3797 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3798 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3799 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003800 Args.push_back(&GtidArg);
3801 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003802 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003803 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003804 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3805 auto *TaskEntry =
3806 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3807 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003808 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003809 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003810 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3811
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003812 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003813 // tt,
3814 // For taskloops:
3815 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3816 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003817 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003818 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003819 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3820 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3821 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003822 auto *KmpTaskTWithPrivatesQTyRD =
3823 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003824 LValue Base =
3825 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003826 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3827 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3828 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003829 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003830
3831 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3832 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003833 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003834 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003835 CGF.ConvertTypeForMem(SharedsPtrTy));
3836
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003837 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3838 llvm::Value *PrivatesParam;
3839 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3840 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3841 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003842 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003843 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003844 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003845
Alexey Bataev7292c292016-04-25 12:22:29 +00003846 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3847 TaskPrivatesMap,
3848 CGF.Builder
3849 .CreatePointerBitCastOrAddrSpaceCast(
3850 TDBase.getAddress(), CGF.VoidPtrTy)
3851 .getPointer()};
3852 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3853 std::end(CommonArgs));
3854 if (isOpenMPTaskLoopDirective(Kind)) {
3855 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3856 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3857 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3858 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3859 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3860 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3861 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3862 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3863 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3864 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3865 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3866 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003867 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3868 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3869 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003870 CallArgs.push_back(LBParam);
3871 CallArgs.push_back(UBParam);
3872 CallArgs.push_back(StParam);
3873 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003874 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003875 }
3876 CallArgs.push_back(SharedsParam);
3877
Alexey Bataev3c595a62017-08-14 15:01:03 +00003878 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3879 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003880 CGF.EmitStoreThroughLValue(
3881 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003882 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003883 CGF.FinishFunction();
3884 return TaskEntry;
3885}
3886
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003887static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3888 SourceLocation Loc,
3889 QualType KmpInt32Ty,
3890 QualType KmpTaskTWithPrivatesPtrQTy,
3891 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003892 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003893 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003894 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3895 ImplicitParamDecl::Other);
3896 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3897 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3898 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003899 Args.push_back(&GtidArg);
3900 Args.push_back(&TaskTypeArg);
3901 FunctionType::ExtInfo Info;
3902 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003903 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003904 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3905 auto *DestructorFn =
3906 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3907 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003908 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3909 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003910 CodeGenFunction CGF(CGM);
3911 CGF.disableDebugInfo();
3912 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3913 Args);
3914
Alexey Bataev31300ed2016-02-04 11:27:03 +00003915 LValue Base = CGF.EmitLoadOfPointerLValue(
3916 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3917 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003918 auto *KmpTaskTWithPrivatesQTyRD =
3919 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3920 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003921 Base = CGF.EmitLValueForField(Base, *FI);
3922 for (auto *Field :
3923 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3924 if (auto DtorKind = Field->getType().isDestructedType()) {
3925 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3926 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3927 }
3928 }
3929 CGF.FinishFunction();
3930 return DestructorFn;
3931}
3932
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003933/// \brief Emit a privates mapping function for correct handling of private and
3934/// firstprivate variables.
3935/// \code
3936/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3937/// **noalias priv1,..., <tyn> **noalias privn) {
3938/// *priv1 = &.privates.priv1;
3939/// ...;
3940/// *privn = &.privates.privn;
3941/// }
3942/// \endcode
3943static llvm::Value *
3944emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003945 ArrayRef<const Expr *> PrivateVars,
3946 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003947 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003948 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003949 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003950 auto &C = CGM.getContext();
3951 FunctionArgList Args;
3952 ImplicitParamDecl TaskPrivatesArg(
3953 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003954 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3955 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003956 Args.push_back(&TaskPrivatesArg);
3957 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3958 unsigned Counter = 1;
3959 for (auto *E: PrivateVars) {
3960 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003961 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3962 C.getPointerType(C.getPointerType(E->getType()))
3963 .withConst()
3964 .withRestrict(),
3965 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003966 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3967 PrivateVarsPos[VD] = Counter;
3968 ++Counter;
3969 }
3970 for (auto *E : FirstprivateVars) {
3971 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003972 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3973 C.getPointerType(C.getPointerType(E->getType()))
3974 .withConst()
3975 .withRestrict(),
3976 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003977 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3978 PrivateVarsPos[VD] = Counter;
3979 ++Counter;
3980 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003981 for (auto *E: LastprivateVars) {
3982 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003983 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3984 C.getPointerType(C.getPointerType(E->getType()))
3985 .withConst()
3986 .withRestrict(),
3987 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003988 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3989 PrivateVarsPos[VD] = Counter;
3990 ++Counter;
3991 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003992 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003993 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003994 auto *TaskPrivatesMapTy =
3995 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3996 auto *TaskPrivatesMap = llvm::Function::Create(
3997 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3998 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003999 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4000 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004001 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004002 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004003 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004004 CodeGenFunction CGF(CGM);
4005 CGF.disableDebugInfo();
4006 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4007 TaskPrivatesMapFnInfo, Args);
4008
4009 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004010 LValue Base = CGF.EmitLoadOfPointerLValue(
4011 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4012 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004013 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4014 Counter = 0;
4015 for (auto *Field : PrivatesQTyRD->fields()) {
4016 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4017 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004018 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004019 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4020 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004021 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004022 ++Counter;
4023 }
4024 CGF.FinishFunction();
4025 return TaskPrivatesMap;
4026}
4027
Alexey Bataev9e034042015-05-05 04:05:12 +00004028static int array_pod_sort_comparator(const PrivateDataTy *P1,
4029 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004030 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4031}
4032
Alexey Bataevf93095a2016-05-05 08:46:22 +00004033/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004034static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004035 const OMPExecutableDirective &D,
4036 Address KmpTaskSharedsPtr, LValue TDBase,
4037 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4038 QualType SharedsTy, QualType SharedsPtrTy,
4039 const OMPTaskDataTy &Data,
4040 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4041 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004042 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4043 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4044 LValue SrcBase;
4045 if (!Data.FirstprivateVars.empty()) {
4046 SrcBase = CGF.MakeAddrLValue(
4047 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4048 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4049 SharedsTy);
4050 }
4051 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4052 cast<CapturedStmt>(*D.getAssociatedStmt()));
4053 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4054 for (auto &&Pair : Privates) {
4055 auto *VD = Pair.second.PrivateCopy;
4056 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004057 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4058 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004059 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004060 if (auto *Elem = Pair.second.PrivateElemInit) {
4061 auto *OriginalVD = Pair.second.Original;
4062 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4063 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4064 SharedRefLValue = CGF.MakeAddrLValue(
4065 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004066 SharedRefLValue.getType(),
4067 LValueBaseInfo(AlignmentSource::Decl,
4068 SharedRefLValue.getBaseInfo().getMayAlias()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004069 QualType Type = OriginalVD->getType();
4070 if (Type->isArrayType()) {
4071 // Initialize firstprivate array.
4072 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4073 // Perform simple memcpy.
4074 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4075 SharedRefLValue.getAddress(), Type);
4076 } else {
4077 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004078 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004079 CGF.EmitOMPAggregateAssign(
4080 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4081 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4082 Address SrcElement) {
4083 // Clean up any temporaries needed by the initialization.
4084 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4085 InitScope.addPrivate(
4086 Elem, [SrcElement]() -> Address { return SrcElement; });
4087 (void)InitScope.Privatize();
4088 // Emit initialization for single element.
4089 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4090 CGF, &CapturesInfo);
4091 CGF.EmitAnyExprToMem(Init, DestElement,
4092 Init->getType().getQualifiers(),
4093 /*IsInitializer=*/false);
4094 });
4095 }
4096 } else {
4097 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4098 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4099 return SharedRefLValue.getAddress();
4100 });
4101 (void)InitScope.Privatize();
4102 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4103 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4104 /*capturedByInit=*/false);
4105 }
4106 } else
4107 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4108 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004109 ++FI;
4110 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004111}
4112
4113/// Check if duplication function is required for taskloops.
4114static bool checkInitIsRequired(CodeGenFunction &CGF,
4115 ArrayRef<PrivateDataTy> Privates) {
4116 bool InitRequired = false;
4117 for (auto &&Pair : Privates) {
4118 auto *VD = Pair.second.PrivateCopy;
4119 auto *Init = VD->getAnyInitializer();
4120 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4121 !CGF.isTrivialInitializer(Init));
4122 }
4123 return InitRequired;
4124}
4125
4126
4127/// Emit task_dup function (for initialization of
4128/// private/firstprivate/lastprivate vars and last_iter flag)
4129/// \code
4130/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4131/// lastpriv) {
4132/// // setup lastprivate flag
4133/// task_dst->last = lastpriv;
4134/// // could be constructor calls here...
4135/// }
4136/// \endcode
4137static llvm::Value *
4138emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4139 const OMPExecutableDirective &D,
4140 QualType KmpTaskTWithPrivatesPtrQTy,
4141 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4142 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4143 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4144 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4145 auto &C = CGM.getContext();
4146 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004147 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4148 KmpTaskTWithPrivatesPtrQTy,
4149 ImplicitParamDecl::Other);
4150 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4151 KmpTaskTWithPrivatesPtrQTy,
4152 ImplicitParamDecl::Other);
4153 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4154 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004155 Args.push_back(&DstArg);
4156 Args.push_back(&SrcArg);
4157 Args.push_back(&LastprivArg);
4158 auto &TaskDupFnInfo =
4159 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4160 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4161 auto *TaskDup =
4162 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4163 ".omp_task_dup.", &CGM.getModule());
4164 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4165 CodeGenFunction CGF(CGM);
4166 CGF.disableDebugInfo();
4167 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4168
4169 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4170 CGF.GetAddrOfLocalVar(&DstArg),
4171 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4172 // task_dst->liter = lastpriv;
4173 if (WithLastIter) {
4174 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4175 LValue Base = CGF.EmitLValueForField(
4176 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4177 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4178 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4179 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4180 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4181 }
4182
4183 // Emit initial values for private copies (if any).
4184 assert(!Privates.empty());
4185 Address KmpTaskSharedsPtr = Address::invalid();
4186 if (!Data.FirstprivateVars.empty()) {
4187 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4188 CGF.GetAddrOfLocalVar(&SrcArg),
4189 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4190 LValue Base = CGF.EmitLValueForField(
4191 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4192 KmpTaskSharedsPtr = Address(
4193 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4194 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4195 KmpTaskTShareds)),
4196 Loc),
4197 CGF.getNaturalTypeAlignment(SharedsTy));
4198 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004199 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4200 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004201 CGF.FinishFunction();
4202 return TaskDup;
4203}
4204
Alexey Bataev8a831592016-05-10 10:36:51 +00004205/// Checks if destructor function is required to be generated.
4206/// \return true if cleanups are required, false otherwise.
4207static bool
4208checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4209 bool NeedsCleanup = false;
4210 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4211 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4212 for (auto *FD : PrivateRD->fields()) {
4213 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4214 if (NeedsCleanup)
4215 break;
4216 }
4217 return NeedsCleanup;
4218}
4219
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004220CGOpenMPRuntime::TaskResultTy
4221CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4222 const OMPExecutableDirective &D,
4223 llvm::Value *TaskFunction, QualType SharedsTy,
4224 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004225 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004226 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004227 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004228 auto I = Data.PrivateCopies.begin();
4229 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004230 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4231 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004232 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004233 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4234 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004235 ++I;
4236 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004237 I = Data.FirstprivateCopies.begin();
4238 auto IElemInitRef = Data.FirstprivateInits.begin();
4239 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004240 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4241 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004242 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004243 PrivateHelpersTy(
4244 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4245 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004246 ++I;
4247 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004248 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004249 I = Data.LastprivateCopies.begin();
4250 for (auto *E : Data.LastprivateVars) {
4251 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4252 Privates.push_back(std::make_pair(
4253 C.getDeclAlign(VD),
4254 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4255 /*PrivateElemInit=*/nullptr)));
4256 ++I;
4257 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004258 llvm::array_pod_sort(Privates.begin(), Privates.end(),
4259 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004260 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4261 // Build type kmp_routine_entry_t (if not built yet).
4262 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004263 // Build type kmp_task_t (if not built yet).
4264 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004265 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4266 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004267 }
4268 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004269 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004270 auto *KmpTaskTWithPrivatesQTyRD =
4271 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4272 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4273 QualType KmpTaskTWithPrivatesPtrQTy =
4274 C.getPointerType(KmpTaskTWithPrivatesQTy);
4275 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4276 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004277 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004278 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4279
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004280 // Emit initial values for private copies (if any).
4281 llvm::Value *TaskPrivatesMap = nullptr;
4282 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004283 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004284 if (!Privates.empty()) {
4285 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004286 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4287 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4288 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004289 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4290 TaskPrivatesMap, TaskPrivatesMapTy);
4291 } else {
4292 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4293 cast<llvm::PointerType>(TaskPrivatesMapTy));
4294 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004295 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4296 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004297 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004298 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4299 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4300 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004301
4302 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4303 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4304 // kmp_routine_entry_t *task_entry);
4305 // Task flags. Format is taken from
4306 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4307 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004308 enum {
4309 TiedFlag = 0x1,
4310 FinalFlag = 0x2,
4311 DestructorsFlag = 0x8,
4312 PriorityFlag = 0x20
4313 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004314 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004315 bool NeedsCleanup = false;
4316 if (!Privates.empty()) {
4317 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4318 if (NeedsCleanup)
4319 Flags = Flags | DestructorsFlag;
4320 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004321 if (Data.Priority.getInt())
4322 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004323 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004324 Data.Final.getPointer()
4325 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004326 CGF.Builder.getInt32(FinalFlag),
4327 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004328 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004329 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004330 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004331 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4332 getThreadID(CGF, Loc), TaskFlags,
4333 KmpTaskTWithPrivatesTySize, SharedsSize,
4334 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4335 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004336 auto *NewTask = CGF.EmitRuntimeCall(
4337 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004338 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4339 NewTask, KmpTaskTWithPrivatesPtrTy);
4340 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4341 KmpTaskTWithPrivatesQTy);
4342 LValue TDBase =
4343 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004344 // Fill the data in the resulting kmp_task_t record.
4345 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004346 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004347 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004348 KmpTaskSharedsPtr =
4349 Address(CGF.EmitLoadOfScalar(
4350 CGF.EmitLValueForField(
4351 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4352 KmpTaskTShareds)),
4353 Loc),
4354 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004355 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004356 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004357 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004358 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004359 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004360 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4361 SharedsTy, SharedsPtrTy, Data, Privates,
4362 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004363 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4364 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4365 Result.TaskDupFn = emitTaskDupFunction(
4366 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4367 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4368 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004369 }
4370 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004371 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4372 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004373 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004374 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4375 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4376 if (NeedsCleanup) {
4377 llvm::Value *DestructorFn = emitDestructorsFunction(
4378 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4379 KmpTaskTWithPrivatesQTy);
4380 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4381 LValue DestructorsLV = CGF.EmitLValueForField(
4382 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4383 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4384 DestructorFn, KmpRoutineEntryPtrTy),
4385 DestructorsLV);
4386 }
4387 // Set priority.
4388 if (Data.Priority.getInt()) {
4389 LValue Data2LV = CGF.EmitLValueForField(
4390 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4391 LValue PriorityLV = CGF.EmitLValueForField(
4392 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4393 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4394 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004395 Result.NewTask = NewTask;
4396 Result.TaskEntry = TaskEntry;
4397 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4398 Result.TDBase = TDBase;
4399 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4400 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004401}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004402
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004403void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4404 const OMPExecutableDirective &D,
4405 llvm::Value *TaskFunction,
4406 QualType SharedsTy, Address Shareds,
4407 const Expr *IfCond,
4408 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004409 if (!CGF.HaveInsertPoint())
4410 return;
4411
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004412 TaskResultTy Result =
4413 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4414 llvm::Value *NewTask = Result.NewTask;
4415 llvm::Value *TaskEntry = Result.TaskEntry;
4416 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4417 LValue TDBase = Result.TDBase;
4418 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004419 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004420 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004421 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004422 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004423 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004424 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004425 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004426 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4427 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004428 QualType FlagsTy =
4429 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004430 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4431 if (KmpDependInfoTy.isNull()) {
4432 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4433 KmpDependInfoRD->startDefinition();
4434 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4435 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4436 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4437 KmpDependInfoRD->completeDefinition();
4438 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004439 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004440 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004441 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004442 // Define type kmp_depend_info[<Dependences.size()>];
4443 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004444 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004445 ArrayType::Normal, /*IndexTypeQuals=*/0);
4446 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004447 DependenciesArray =
4448 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004449 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004450 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004451 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004452 llvm::Value *Size;
4453 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004454 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4455 LValue UpAddrLVal =
4456 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4457 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004458 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004459 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004460 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004461 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4462 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004463 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004464 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004465 auto Base = CGF.MakeAddrLValue(
4466 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004467 KmpDependInfoTy);
4468 // deps[i].base_addr = &<Dependences[i].second>;
4469 auto BaseAddrLVal = CGF.EmitLValueForField(
4470 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004471 CGF.EmitStoreOfScalar(
4472 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4473 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004474 // deps[i].len = sizeof(<Dependences[i].second>);
4475 auto LenLVal = CGF.EmitLValueForField(
4476 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4477 CGF.EmitStoreOfScalar(Size, LenLVal);
4478 // deps[i].flags = <Dependences[i].first>;
4479 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004480 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004481 case OMPC_DEPEND_in:
4482 DepKind = DepIn;
4483 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004484 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004485 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004486 case OMPC_DEPEND_inout:
4487 DepKind = DepInOut;
4488 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004489 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004490 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004491 case OMPC_DEPEND_unknown:
4492 llvm_unreachable("Unknown task dependence type");
4493 }
4494 auto FlagsLVal = CGF.EmitLValueForField(
4495 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4496 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4497 FlagsLVal);
4498 }
John McCall7f416cc2015-09-08 08:05:57 +00004499 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4500 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004501 CGF.VoidPtrTy);
4502 }
4503
Alexey Bataev62b63b12015-03-10 07:28:44 +00004504 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4505 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004506 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4507 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4508 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4509 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004510 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004511 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004512 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4513 llvm::Value *DepTaskArgs[7];
4514 if (NumDependencies) {
4515 DepTaskArgs[0] = UpLoc;
4516 DepTaskArgs[1] = ThreadID;
4517 DepTaskArgs[2] = NewTask;
4518 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4519 DepTaskArgs[4] = DependenciesArray.getPointer();
4520 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4521 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4522 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004523 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4524 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004525 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004526 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004527 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4528 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4529 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4530 }
John McCall7f416cc2015-09-08 08:05:57 +00004531 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004532 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004533 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004534 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004535 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004536 TaskArgs);
4537 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004538 // Check if parent region is untied and build return for untied task;
4539 if (auto *Region =
4540 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4541 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004542 };
John McCall7f416cc2015-09-08 08:05:57 +00004543
4544 llvm::Value *DepWaitTaskArgs[6];
4545 if (NumDependencies) {
4546 DepWaitTaskArgs[0] = UpLoc;
4547 DepWaitTaskArgs[1] = ThreadID;
4548 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4549 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4550 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4551 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4552 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004553 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004554 NumDependencies, &DepWaitTaskArgs,
4555 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004556 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004557 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4558 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4559 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4560 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4561 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004562 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004563 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004564 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004565 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004566 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4567 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004568 Action.Enter(CGF);
4569 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004570 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004571 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004572 };
4573
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004574 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4575 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004576 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4577 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004578 RegionCodeGenTy RCG(CodeGen);
4579 CommonActionTy Action(
4580 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4581 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4582 RCG.setAction(Action);
4583 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004584 };
John McCall7f416cc2015-09-08 08:05:57 +00004585
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004586 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004587 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004588 else {
4589 RegionCodeGenTy ThenRCG(ThenCodeGen);
4590 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004591 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004592}
4593
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004594void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4595 const OMPLoopDirective &D,
4596 llvm::Value *TaskFunction,
4597 QualType SharedsTy, Address Shareds,
4598 const Expr *IfCond,
4599 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004600 if (!CGF.HaveInsertPoint())
4601 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004602 TaskResultTy Result =
4603 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004604 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4605 // libcall.
4606 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4607 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4608 // sched, kmp_uint64 grainsize, void *task_dup);
4609 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4610 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4611 llvm::Value *IfVal;
4612 if (IfCond) {
4613 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4614 /*isSigned=*/true);
4615 } else
4616 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4617
4618 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004619 Result.TDBase,
4620 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004621 auto *LBVar =
4622 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4623 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4624 /*IsInitializer=*/true);
4625 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004626 Result.TDBase,
4627 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004628 auto *UBVar =
4629 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4630 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4631 /*IsInitializer=*/true);
4632 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004633 Result.TDBase,
4634 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004635 auto *StVar =
4636 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4637 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4638 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004639 // Store reductions address.
4640 LValue RedLVal = CGF.EmitLValueForField(
4641 Result.TDBase,
4642 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4643 if (Data.Reductions)
4644 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4645 else {
4646 CGF.EmitNullInitialization(RedLVal.getAddress(),
4647 CGF.getContext().VoidPtrTy);
4648 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004649 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004650 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004651 UpLoc,
4652 ThreadID,
4653 Result.NewTask,
4654 IfVal,
4655 LBLVal.getPointer(),
4656 UBLVal.getPointer(),
4657 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4658 llvm::ConstantInt::getNullValue(
4659 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004660 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004661 CGF.IntTy, Data.Schedule.getPointer()
4662 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004663 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004664 Data.Schedule.getPointer()
4665 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004666 /*isSigned=*/false)
4667 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004668 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4669 Result.TaskDupFn, CGF.VoidPtrTy)
4670 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004671 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4672}
4673
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004674/// \brief Emit reduction operation for each element of array (required for
4675/// array sections) LHS op = RHS.
4676/// \param Type Type of array.
4677/// \param LHSVar Variable on the left side of the reduction operation
4678/// (references element of array in original variable).
4679/// \param RHSVar Variable on the right side of the reduction operation
4680/// (references element of array in original variable).
4681/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4682/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004683static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004684 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4685 const VarDecl *RHSVar,
4686 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4687 const Expr *, const Expr *)> &RedOpGen,
4688 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4689 const Expr *UpExpr = nullptr) {
4690 // Perform element-by-element initialization.
4691 QualType ElementTy;
4692 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4693 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4694
4695 // Drill down to the base element type on both arrays.
4696 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4697 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4698
4699 auto RHSBegin = RHSAddr.getPointer();
4700 auto LHSBegin = LHSAddr.getPointer();
4701 // Cast from pointer to array type to pointer to single element.
4702 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4703 // The basic structure here is a while-do loop.
4704 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4705 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4706 auto IsEmpty =
4707 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4708 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4709
4710 // Enter the loop body, making that address the current address.
4711 auto EntryBB = CGF.Builder.GetInsertBlock();
4712 CGF.EmitBlock(BodyBB);
4713
4714 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4715
4716 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4717 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4718 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4719 Address RHSElementCurrent =
4720 Address(RHSElementPHI,
4721 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4722
4723 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4724 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4725 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4726 Address LHSElementCurrent =
4727 Address(LHSElementPHI,
4728 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4729
4730 // Emit copy.
4731 CodeGenFunction::OMPPrivateScope Scope(CGF);
4732 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4733 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4734 Scope.Privatize();
4735 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4736 Scope.ForceCleanup();
4737
4738 // Shift the address forward by one element.
4739 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4740 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4741 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4742 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4743 // Check whether we've reached the end.
4744 auto Done =
4745 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4746 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4747 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4748 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4749
4750 // Done.
4751 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4752}
4753
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004754/// Emit reduction combiner. If the combiner is a simple expression emit it as
4755/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4756/// UDR combiner function.
4757static void emitReductionCombiner(CodeGenFunction &CGF,
4758 const Expr *ReductionOp) {
4759 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4760 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4761 if (auto *DRE =
4762 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4763 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4764 std::pair<llvm::Function *, llvm::Function *> Reduction =
4765 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4766 RValue Func = RValue::get(Reduction.first);
4767 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4768 CGF.EmitIgnoredExpr(ReductionOp);
4769 return;
4770 }
4771 CGF.EmitIgnoredExpr(ReductionOp);
4772}
4773
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004774llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4775 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4776 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4777 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004778 auto &C = CGM.getContext();
4779
4780 // void reduction_func(void *LHSArg, void *RHSArg);
4781 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004782 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4783 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004784 Args.push_back(&LHSArg);
4785 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004786 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004787 auto *Fn = llvm::Function::Create(
4788 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4789 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004790 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004791 CodeGenFunction CGF(CGM);
4792 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4793
4794 // Dst = (void*[n])(LHSArg);
4795 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004796 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4797 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4798 ArgsType), CGF.getPointerAlign());
4799 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4800 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4801 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004802
4803 // ...
4804 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4805 // ...
4806 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004807 auto IPriv = Privates.begin();
4808 unsigned Idx = 0;
4809 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004810 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4811 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004812 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004813 });
4814 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4815 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004816 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004817 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004818 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004819 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004820 // Get array size and emit VLA type.
4821 ++Idx;
4822 Address Elem =
4823 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4824 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004825 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4826 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004827 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004828 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004829 CGF.EmitVariablyModifiedType(PrivTy);
4830 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004831 }
4832 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004833 IPriv = Privates.begin();
4834 auto ILHS = LHSExprs.begin();
4835 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004836 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004837 if ((*IPriv)->getType()->isArrayType()) {
4838 // Emit reduction for array section.
4839 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4840 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004841 EmitOMPAggregateReduction(
4842 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4843 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4844 emitReductionCombiner(CGF, E);
4845 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004846 } else
4847 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004848 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004849 ++IPriv;
4850 ++ILHS;
4851 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004852 }
4853 Scope.ForceCleanup();
4854 CGF.FinishFunction();
4855 return Fn;
4856}
4857
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004858void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4859 const Expr *ReductionOp,
4860 const Expr *PrivateRef,
4861 const DeclRefExpr *LHS,
4862 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004863 if (PrivateRef->getType()->isArrayType()) {
4864 // Emit reduction for array section.
4865 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4866 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4867 EmitOMPAggregateReduction(
4868 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4869 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4870 emitReductionCombiner(CGF, ReductionOp);
4871 });
4872 } else
4873 // Emit reduction for array subscript or single variable.
4874 emitReductionCombiner(CGF, ReductionOp);
4875}
4876
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004877void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004878 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004879 ArrayRef<const Expr *> LHSExprs,
4880 ArrayRef<const Expr *> RHSExprs,
4881 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004882 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004883 if (!CGF.HaveInsertPoint())
4884 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004885
4886 bool WithNowait = Options.WithNowait;
4887 bool SimpleReduction = Options.SimpleReduction;
4888
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004889 // Next code should be emitted for reduction:
4890 //
4891 // static kmp_critical_name lock = { 0 };
4892 //
4893 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4894 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4895 // ...
4896 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4897 // *(Type<n>-1*)rhs[<n>-1]);
4898 // }
4899 //
4900 // ...
4901 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4902 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4903 // RedList, reduce_func, &<lock>)) {
4904 // case 1:
4905 // ...
4906 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4907 // ...
4908 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4909 // break;
4910 // case 2:
4911 // ...
4912 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4913 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004914 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004915 // break;
4916 // default:;
4917 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004918 //
4919 // if SimpleReduction is true, only the next code is generated:
4920 // ...
4921 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4922 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004923
4924 auto &C = CGM.getContext();
4925
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004926 if (SimpleReduction) {
4927 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004928 auto IPriv = Privates.begin();
4929 auto ILHS = LHSExprs.begin();
4930 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004931 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004932 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4933 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004934 ++IPriv;
4935 ++ILHS;
4936 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004937 }
4938 return;
4939 }
4940
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004941 // 1. Build a list of reduction variables.
4942 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004943 auto Size = RHSExprs.size();
4944 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004945 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004946 // Reserve place for array size.
4947 ++Size;
4948 }
4949 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004950 QualType ReductionArrayTy =
4951 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4952 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004953 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004954 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004955 auto IPriv = Privates.begin();
4956 unsigned Idx = 0;
4957 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004958 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004959 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004960 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004961 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004962 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4963 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004964 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004965 // Store array size.
4966 ++Idx;
4967 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4968 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004969 llvm::Value *Size = CGF.Builder.CreateIntCast(
4970 CGF.getVLASize(
4971 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4972 .first,
4973 CGF.SizeTy, /*isSigned=*/false);
4974 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4975 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004976 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004977 }
4978
4979 // 2. Emit reduce_func().
4980 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004981 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4982 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004983
4984 // 3. Create static kmp_critical_name lock = { 0 };
4985 auto *Lock = getCriticalRegionLock(".reduction");
4986
4987 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4988 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004989 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004990 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004991 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004992 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4993 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004994 llvm::Value *Args[] = {
4995 IdentTLoc, // ident_t *<loc>
4996 ThreadId, // i32 <gtid>
4997 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4998 ReductionArrayTySize, // size_type sizeof(RedList)
4999 RL, // void *RedList
5000 ReductionFn, // void (*) (void *, void *) <reduce_func>
5001 Lock // kmp_critical_name *&<lock>
5002 };
5003 auto Res = CGF.EmitRuntimeCall(
5004 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5005 : OMPRTL__kmpc_reduce),
5006 Args);
5007
5008 // 5. Build switch(res)
5009 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5010 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5011
5012 // 6. Build case 1:
5013 // ...
5014 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5015 // ...
5016 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5017 // break;
5018 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5019 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5020 CGF.EmitBlock(Case1BB);
5021
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005022 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5023 llvm::Value *EndArgs[] = {
5024 IdentTLoc, // ident_t *<loc>
5025 ThreadId, // i32 <gtid>
5026 Lock // kmp_critical_name *&<lock>
5027 };
5028 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5029 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005030 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005031 auto IPriv = Privates.begin();
5032 auto ILHS = LHSExprs.begin();
5033 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005034 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005035 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5036 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005037 ++IPriv;
5038 ++ILHS;
5039 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005040 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005041 };
5042 RegionCodeGenTy RCG(CodeGen);
5043 CommonActionTy Action(
5044 nullptr, llvm::None,
5045 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5046 : OMPRTL__kmpc_end_reduce),
5047 EndArgs);
5048 RCG.setAction(Action);
5049 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005050
5051 CGF.EmitBranch(DefaultBB);
5052
5053 // 7. Build case 2:
5054 // ...
5055 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5056 // ...
5057 // break;
5058 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5059 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5060 CGF.EmitBlock(Case2BB);
5061
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005062 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5063 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005064 auto ILHS = LHSExprs.begin();
5065 auto IRHS = RHSExprs.begin();
5066 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005067 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005068 const Expr *XExpr = nullptr;
5069 const Expr *EExpr = nullptr;
5070 const Expr *UpExpr = nullptr;
5071 BinaryOperatorKind BO = BO_Comma;
5072 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5073 if (BO->getOpcode() == BO_Assign) {
5074 XExpr = BO->getLHS();
5075 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005076 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005077 }
5078 // Try to emit update expression as a simple atomic.
5079 auto *RHSExpr = UpExpr;
5080 if (RHSExpr) {
5081 // Analyze RHS part of the whole expression.
5082 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5083 RHSExpr->IgnoreParenImpCasts())) {
5084 // If this is a conditional operator, analyze its condition for
5085 // min/max reduction operator.
5086 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005087 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005088 if (auto *BORHS =
5089 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5090 EExpr = BORHS->getRHS();
5091 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005092 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005093 }
5094 if (XExpr) {
5095 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005096 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005097 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5098 const Expr *EExpr, const Expr *UpExpr) {
5099 LValue X = CGF.EmitLValue(XExpr);
5100 RValue E;
5101 if (EExpr)
5102 E = CGF.EmitAnyExpr(EExpr);
5103 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005104 X, E, BO, /*IsXLHSInRHSPart=*/true,
5105 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005106 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005107 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5108 PrivateScope.addPrivate(
5109 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5110 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5111 CGF.emitOMPSimpleStore(
5112 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5113 VD->getType().getNonReferenceType(), Loc);
5114 return LHSTemp;
5115 });
5116 (void)PrivateScope.Privatize();
5117 return CGF.EmitAnyExpr(UpExpr);
5118 });
5119 };
5120 if ((*IPriv)->getType()->isArrayType()) {
5121 // Emit atomic reduction for array section.
5122 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5123 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5124 AtomicRedGen, XExpr, EExpr, UpExpr);
5125 } else
5126 // Emit atomic reduction for array subscript or single variable.
5127 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5128 } else {
5129 // Emit as a critical region.
5130 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5131 const Expr *, const Expr *) {
5132 auto &RT = CGF.CGM.getOpenMPRuntime();
5133 RT.emitCriticalRegion(
5134 CGF, ".atomic_reduction",
5135 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5136 Action.Enter(CGF);
5137 emitReductionCombiner(CGF, E);
5138 },
5139 Loc);
5140 };
5141 if ((*IPriv)->getType()->isArrayType()) {
5142 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5143 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5144 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5145 CritRedGen);
5146 } else
5147 CritRedGen(CGF, nullptr, nullptr, nullptr);
5148 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005149 ++ILHS;
5150 ++IRHS;
5151 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005152 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005153 };
5154 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5155 if (!WithNowait) {
5156 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5157 llvm::Value *EndArgs[] = {
5158 IdentTLoc, // ident_t *<loc>
5159 ThreadId, // i32 <gtid>
5160 Lock // kmp_critical_name *&<lock>
5161 };
5162 CommonActionTy Action(nullptr, llvm::None,
5163 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5164 EndArgs);
5165 AtomicRCG.setAction(Action);
5166 AtomicRCG(CGF);
5167 } else
5168 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005169
5170 CGF.EmitBranch(DefaultBB);
5171 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5172}
5173
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005174/// Generates unique name for artificial threadprivate variables.
5175/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5176static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5177 unsigned N) {
5178 SmallString<256> Buffer;
5179 llvm::raw_svector_ostream Out(Buffer);
5180 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5181 return Out.str();
5182}
5183
5184/// Emits reduction initializer function:
5185/// \code
5186/// void @.red_init(void* %arg) {
5187/// %0 = bitcast void* %arg to <type>*
5188/// store <type> <init>, <type>* %0
5189/// ret void
5190/// }
5191/// \endcode
5192static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5193 SourceLocation Loc,
5194 ReductionCodeGen &RCG, unsigned N) {
5195 auto &C = CGM.getContext();
5196 FunctionArgList Args;
5197 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5198 Args.emplace_back(&Param);
5199 auto &FnInfo =
5200 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5201 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5202 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5203 ".red_init.", &CGM.getModule());
5204 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5205 CodeGenFunction CGF(CGM);
5206 CGF.disableDebugInfo();
5207 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5208 Address PrivateAddr = CGF.EmitLoadOfPointer(
5209 CGF.GetAddrOfLocalVar(&Param),
5210 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5211 llvm::Value *Size = nullptr;
5212 // If the size of the reduction item is non-constant, load it from global
5213 // threadprivate variable.
5214 if (RCG.getSizes(N).second) {
5215 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5216 CGF, CGM.getContext().getSizeType(),
5217 generateUniqueName("reduction_size", Loc, N));
5218 Size =
5219 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5220 CGM.getContext().getSizeType(), SourceLocation());
5221 }
5222 RCG.emitAggregateType(CGF, N, Size);
5223 LValue SharedLVal;
5224 // If initializer uses initializer from declare reduction construct, emit a
5225 // pointer to the address of the original reduction item (reuired by reduction
5226 // initializer)
5227 if (RCG.usesReductionInitializer(N)) {
5228 Address SharedAddr =
5229 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5230 CGF, CGM.getContext().VoidPtrTy,
5231 generateUniqueName("reduction", Loc, N));
5232 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5233 } else {
5234 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5235 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5236 CGM.getContext().VoidPtrTy);
5237 }
5238 // Emit the initializer:
5239 // %0 = bitcast void* %arg to <type>*
5240 // store <type> <init>, <type>* %0
5241 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5242 [](CodeGenFunction &) { return false; });
5243 CGF.FinishFunction();
5244 return Fn;
5245}
5246
5247/// Emits reduction combiner function:
5248/// \code
5249/// void @.red_comb(void* %arg0, void* %arg1) {
5250/// %lhs = bitcast void* %arg0 to <type>*
5251/// %rhs = bitcast void* %arg1 to <type>*
5252/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5253/// store <type> %2, <type>* %lhs
5254/// ret void
5255/// }
5256/// \endcode
5257static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5258 SourceLocation Loc,
5259 ReductionCodeGen &RCG, unsigned N,
5260 const Expr *ReductionOp,
5261 const Expr *LHS, const Expr *RHS,
5262 const Expr *PrivateRef) {
5263 auto &C = CGM.getContext();
5264 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5265 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5266 FunctionArgList Args;
5267 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5268 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5269 Args.emplace_back(&ParamInOut);
5270 Args.emplace_back(&ParamIn);
5271 auto &FnInfo =
5272 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5273 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5274 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5275 ".red_comb.", &CGM.getModule());
5276 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5277 CodeGenFunction CGF(CGM);
5278 CGF.disableDebugInfo();
5279 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5280 llvm::Value *Size = nullptr;
5281 // If the size of the reduction item is non-constant, load it from global
5282 // threadprivate variable.
5283 if (RCG.getSizes(N).second) {
5284 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5285 CGF, CGM.getContext().getSizeType(),
5286 generateUniqueName("reduction_size", Loc, N));
5287 Size =
5288 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5289 CGM.getContext().getSizeType(), SourceLocation());
5290 }
5291 RCG.emitAggregateType(CGF, N, Size);
5292 // Remap lhs and rhs variables to the addresses of the function arguments.
5293 // %lhs = bitcast void* %arg0 to <type>*
5294 // %rhs = bitcast void* %arg1 to <type>*
5295 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5296 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5297 // Pull out the pointer to the variable.
5298 Address PtrAddr = CGF.EmitLoadOfPointer(
5299 CGF.GetAddrOfLocalVar(&ParamInOut),
5300 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5301 return CGF.Builder.CreateElementBitCast(
5302 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5303 });
5304 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5305 // Pull out the pointer to the variable.
5306 Address PtrAddr = CGF.EmitLoadOfPointer(
5307 CGF.GetAddrOfLocalVar(&ParamIn),
5308 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5309 return CGF.Builder.CreateElementBitCast(
5310 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5311 });
5312 PrivateScope.Privatize();
5313 // Emit the combiner body:
5314 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5315 // store <type> %2, <type>* %lhs
5316 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5317 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5318 cast<DeclRefExpr>(RHS));
5319 CGF.FinishFunction();
5320 return Fn;
5321}
5322
5323/// Emits reduction finalizer function:
5324/// \code
5325/// void @.red_fini(void* %arg) {
5326/// %0 = bitcast void* %arg to <type>*
5327/// <destroy>(<type>* %0)
5328/// ret void
5329/// }
5330/// \endcode
5331static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5332 SourceLocation Loc,
5333 ReductionCodeGen &RCG, unsigned N) {
5334 if (!RCG.needCleanups(N))
5335 return nullptr;
5336 auto &C = CGM.getContext();
5337 FunctionArgList Args;
5338 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5339 Args.emplace_back(&Param);
5340 auto &FnInfo =
5341 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5342 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5343 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5344 ".red_fini.", &CGM.getModule());
5345 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5346 CodeGenFunction CGF(CGM);
5347 CGF.disableDebugInfo();
5348 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5349 Address PrivateAddr = CGF.EmitLoadOfPointer(
5350 CGF.GetAddrOfLocalVar(&Param),
5351 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5352 llvm::Value *Size = nullptr;
5353 // If the size of the reduction item is non-constant, load it from global
5354 // threadprivate variable.
5355 if (RCG.getSizes(N).second) {
5356 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5357 CGF, CGM.getContext().getSizeType(),
5358 generateUniqueName("reduction_size", Loc, N));
5359 Size =
5360 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5361 CGM.getContext().getSizeType(), SourceLocation());
5362 }
5363 RCG.emitAggregateType(CGF, N, Size);
5364 // Emit the finalizer body:
5365 // <destroy>(<type>* %0)
5366 RCG.emitCleanups(CGF, N, PrivateAddr);
5367 CGF.FinishFunction();
5368 return Fn;
5369}
5370
5371llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5372 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5373 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5374 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5375 return nullptr;
5376
5377 // Build typedef struct:
5378 // kmp_task_red_input {
5379 // void *reduce_shar; // shared reduction item
5380 // size_t reduce_size; // size of data item
5381 // void *reduce_init; // data initialization routine
5382 // void *reduce_fini; // data finalization routine
5383 // void *reduce_comb; // data combiner routine
5384 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5385 // } kmp_task_red_input_t;
5386 ASTContext &C = CGM.getContext();
5387 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5388 RD->startDefinition();
5389 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5390 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5391 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5392 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5393 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5394 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5395 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5396 RD->completeDefinition();
5397 QualType RDType = C.getRecordType(RD);
5398 unsigned Size = Data.ReductionVars.size();
5399 llvm::APInt ArraySize(/*numBits=*/64, Size);
5400 QualType ArrayRDType = C.getConstantArrayType(
5401 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5402 // kmp_task_red_input_t .rd_input.[Size];
5403 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5404 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5405 Data.ReductionOps);
5406 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5407 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5408 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5409 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5410 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5411 TaskRedInput.getPointer(), Idxs,
5412 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5413 ".rd_input.gep.");
5414 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5415 // ElemLVal.reduce_shar = &Shareds[Cnt];
5416 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5417 RCG.emitSharedLValue(CGF, Cnt);
5418 llvm::Value *CastedShared =
5419 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5420 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5421 RCG.emitAggregateType(CGF, Cnt);
5422 llvm::Value *SizeValInChars;
5423 llvm::Value *SizeVal;
5424 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5425 // We use delayed creation/initialization for VLAs, array sections and
5426 // custom reduction initializations. It is required because runtime does not
5427 // provide the way to pass the sizes of VLAs/array sections to
5428 // initializer/combiner/finalizer functions and does not pass the pointer to
5429 // original reduction item to the initializer. Instead threadprivate global
5430 // variables are used to store these values and use them in the functions.
5431 bool DelayedCreation = !!SizeVal;
5432 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5433 /*isSigned=*/false);
5434 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5435 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5436 // ElemLVal.reduce_init = init;
5437 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5438 llvm::Value *InitAddr =
5439 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5440 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5441 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5442 // ElemLVal.reduce_fini = fini;
5443 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5444 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5445 llvm::Value *FiniAddr = Fini
5446 ? CGF.EmitCastToVoidPtr(Fini)
5447 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5448 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5449 // ElemLVal.reduce_comb = comb;
5450 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5451 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5452 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5453 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5454 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5455 // ElemLVal.flags = 0;
5456 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5457 if (DelayedCreation) {
5458 CGF.EmitStoreOfScalar(
5459 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5460 FlagsLVal);
5461 } else
5462 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5463 }
5464 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5465 // *data);
5466 llvm::Value *Args[] = {
5467 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5468 /*isSigned=*/true),
5469 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5470 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5471 CGM.VoidPtrTy)};
5472 return CGF.EmitRuntimeCall(
5473 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5474}
5475
5476void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5477 SourceLocation Loc,
5478 ReductionCodeGen &RCG,
5479 unsigned N) {
5480 auto Sizes = RCG.getSizes(N);
5481 // Emit threadprivate global variable if the type is non-constant
5482 // (Sizes.second = nullptr).
5483 if (Sizes.second) {
5484 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5485 /*isSigned=*/false);
5486 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5487 CGF, CGM.getContext().getSizeType(),
5488 generateUniqueName("reduction_size", Loc, N));
5489 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5490 }
5491 // Store address of the original reduction item if custom initializer is used.
5492 if (RCG.usesReductionInitializer(N)) {
5493 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5494 CGF, CGM.getContext().VoidPtrTy,
5495 generateUniqueName("reduction", Loc, N));
5496 CGF.Builder.CreateStore(
5497 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5498 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5499 SharedAddr, /*IsVolatile=*/false);
5500 }
5501}
5502
5503Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5504 SourceLocation Loc,
5505 llvm::Value *ReductionsPtr,
5506 LValue SharedLVal) {
5507 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5508 // *d);
5509 llvm::Value *Args[] = {
5510 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5511 /*isSigned=*/true),
5512 ReductionsPtr,
5513 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5514 CGM.VoidPtrTy)};
5515 return Address(
5516 CGF.EmitRuntimeCall(
5517 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5518 SharedLVal.getAlignment());
5519}
5520
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005521void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5522 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005523 if (!CGF.HaveInsertPoint())
5524 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005525 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5526 // global_tid);
5527 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5528 // Ignore return result until untied tasks are supported.
5529 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005530 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5531 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005532}
5533
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005534void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005535 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005536 const RegionCodeGenTy &CodeGen,
5537 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005538 if (!CGF.HaveInsertPoint())
5539 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005540 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005541 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005542}
5543
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005544namespace {
5545enum RTCancelKind {
5546 CancelNoreq = 0,
5547 CancelParallel = 1,
5548 CancelLoop = 2,
5549 CancelSections = 3,
5550 CancelTaskgroup = 4
5551};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005552} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005553
5554static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5555 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005556 if (CancelRegion == OMPD_parallel)
5557 CancelKind = CancelParallel;
5558 else if (CancelRegion == OMPD_for)
5559 CancelKind = CancelLoop;
5560 else if (CancelRegion == OMPD_sections)
5561 CancelKind = CancelSections;
5562 else {
5563 assert(CancelRegion == OMPD_taskgroup);
5564 CancelKind = CancelTaskgroup;
5565 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005566 return CancelKind;
5567}
5568
5569void CGOpenMPRuntime::emitCancellationPointCall(
5570 CodeGenFunction &CGF, SourceLocation Loc,
5571 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005572 if (!CGF.HaveInsertPoint())
5573 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005574 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5575 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005576 if (auto *OMPRegionInfo =
5577 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005578 // For 'cancellation point taskgroup', the task region info may not have a
5579 // cancel. This may instead happen in another adjacent task.
5580 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005581 llvm::Value *Args[] = {
5582 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5583 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005584 // Ignore return result until untied tasks are supported.
5585 auto *Result = CGF.EmitRuntimeCall(
5586 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5587 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005588 // exit from construct;
5589 // }
5590 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5591 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5592 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5593 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5594 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005595 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005596 auto CancelDest =
5597 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005598 CGF.EmitBranchThroughCleanup(CancelDest);
5599 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5600 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005601 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005602}
5603
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005604void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005605 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005606 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005607 if (!CGF.HaveInsertPoint())
5608 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005609 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5610 // kmp_int32 cncl_kind);
5611 if (auto *OMPRegionInfo =
5612 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005613 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5614 PrePostActionTy &) {
5615 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005616 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005617 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005618 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5619 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005620 auto *Result = CGF.EmitRuntimeCall(
5621 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005622 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005623 // exit from construct;
5624 // }
5625 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5626 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5627 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5628 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5629 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005630 // exit from construct;
5631 auto CancelDest =
5632 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5633 CGF.EmitBranchThroughCleanup(CancelDest);
5634 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5635 };
5636 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005637 emitOMPIfClause(CGF, IfCond, ThenGen,
5638 [](CodeGenFunction &, PrePostActionTy &) {});
5639 else {
5640 RegionCodeGenTy ThenRCG(ThenGen);
5641 ThenRCG(CGF);
5642 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005643 }
5644}
Samuel Antaobed3c462015-10-02 16:14:20 +00005645
Samuel Antaoee8fb302016-01-06 13:42:12 +00005646/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005647/// consists of the file and device IDs as well as line number associated with
5648/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005649static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5650 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005651 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005652
5653 auto &SM = C.getSourceManager();
5654
5655 // The loc should be always valid and have a file ID (the user cannot use
5656 // #pragma directives in macros)
5657
5658 assert(Loc.isValid() && "Source location is expected to be always valid.");
5659 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5660
5661 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5662 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5663
5664 llvm::sys::fs::UniqueID ID;
5665 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5666 llvm_unreachable("Source file with target region no longer exists!");
5667
5668 DeviceID = ID.getDevice();
5669 FileID = ID.getFile();
5670 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005671}
5672
5673void CGOpenMPRuntime::emitTargetOutlinedFunction(
5674 const OMPExecutableDirective &D, StringRef ParentName,
5675 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005676 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005677 assert(!ParentName.empty() && "Invalid target region parent name!");
5678
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005679 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5680 IsOffloadEntry, CodeGen);
5681}
5682
5683void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5684 const OMPExecutableDirective &D, StringRef ParentName,
5685 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5686 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005687 // Create a unique name for the entry function using the source location
5688 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005689 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005690 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005691 //
5692 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005693 // mangled name of the function that encloses the target region and BB is the
5694 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005695
5696 unsigned DeviceID;
5697 unsigned FileID;
5698 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005699 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005700 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005701 SmallString<64> EntryFnName;
5702 {
5703 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005704 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5705 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005706 }
5707
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005708 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5709
Samuel Antaobed3c462015-10-02 16:14:20 +00005710 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005711 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005712 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005713
Samuel Antao6d004262016-06-16 18:39:34 +00005714 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005715
5716 // If this target outline function is not an offload entry, we don't need to
5717 // register it.
5718 if (!IsOffloadEntry)
5719 return;
5720
5721 // The target region ID is used by the runtime library to identify the current
5722 // target region, so it only has to be unique and not necessarily point to
5723 // anything. It could be the pointer to the outlined function that implements
5724 // the target region, but we aren't using that so that the compiler doesn't
5725 // need to keep that, and could therefore inline the host function if proven
5726 // worthwhile during optimization. In the other hand, if emitting code for the
5727 // device, the ID has to be the function address so that it can retrieved from
5728 // the offloading entry and launched by the runtime library. We also mark the
5729 // outlined function to have external linkage in case we are emitting code for
5730 // the device, because these functions will be entry points to the device.
5731
5732 if (CGM.getLangOpts().OpenMPIsDevice) {
5733 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5734 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5735 } else
5736 OutlinedFnID = new llvm::GlobalVariable(
5737 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5738 llvm::GlobalValue::PrivateLinkage,
5739 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5740
5741 // Register the information for the entry associated with this target region.
5742 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005743 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5744 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005745}
5746
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005747/// discard all CompoundStmts intervening between two constructs
5748static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5749 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5750 Body = CS->body_front();
5751
5752 return Body;
5753}
5754
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005755/// Emit the number of teams for a target directive. Inspect the num_teams
5756/// clause associated with a teams construct combined or closely nested
5757/// with the target directive.
5758///
5759/// Emit a team of size one for directives such as 'target parallel' that
5760/// have no associated teams construct.
5761///
5762/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005763static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005764emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5765 CodeGenFunction &CGF,
5766 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005767
5768 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5769 "teams directive expected to be "
5770 "emitted only for the host!");
5771
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005772 auto &Bld = CGF.Builder;
5773
5774 // If the target directive is combined with a teams directive:
5775 // Return the value in the num_teams clause, if any.
5776 // Otherwise, return 0 to denote the runtime default.
5777 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5778 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5779 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5780 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5781 /*IgnoreResultAssign*/ true);
5782 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5783 /*IsSigned=*/true);
5784 }
5785
5786 // The default value is 0.
5787 return Bld.getInt32(0);
5788 }
5789
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005790 // If the target directive is combined with a parallel directive but not a
5791 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005792 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5793 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005794
5795 // If the current target region has a teams region enclosed, we need to get
5796 // the number of teams to pass to the runtime function call. This is done
5797 // by generating the expression in a inlined region. This is required because
5798 // the expression is captured in the enclosing target environment when the
5799 // teams directive is not combined with target.
5800
5801 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5802
5803 // FIXME: Accommodate other combined directives with teams when they become
5804 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005805 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5806 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005807 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5808 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5809 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5810 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005811 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5812 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005813 }
5814
5815 // If we have an enclosed teams directive but no num_teams clause we use
5816 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005817 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005818 }
5819
5820 // No teams associated with the directive.
5821 return nullptr;
5822}
5823
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005824/// Emit the number of threads for a target directive. Inspect the
5825/// thread_limit clause associated with a teams construct combined or closely
5826/// nested with the target directive.
5827///
5828/// Emit the num_threads clause for directives such as 'target parallel' that
5829/// have no associated teams construct.
5830///
5831/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005832static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005833emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5834 CodeGenFunction &CGF,
5835 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005836
5837 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5838 "teams directive expected to be "
5839 "emitted only for the host!");
5840
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005841 auto &Bld = CGF.Builder;
5842
5843 //
5844 // If the target directive is combined with a teams directive:
5845 // Return the value in the thread_limit clause, if any.
5846 //
5847 // If the target directive is combined with a parallel directive:
5848 // Return the value in the num_threads clause, if any.
5849 //
5850 // If both clauses are set, select the minimum of the two.
5851 //
5852 // If neither teams or parallel combined directives set the number of threads
5853 // in a team, return 0 to denote the runtime default.
5854 //
5855 // If this is not a teams directive return nullptr.
5856
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005857 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5858 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005859 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5860 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005861 llvm::Value *ThreadLimitVal = nullptr;
5862
5863 if (const auto *ThreadLimitClause =
5864 D.getSingleClause<OMPThreadLimitClause>()) {
5865 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5866 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5867 /*IgnoreResultAssign*/ true);
5868 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5869 /*IsSigned=*/true);
5870 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005871
5872 if (const auto *NumThreadsClause =
5873 D.getSingleClause<OMPNumThreadsClause>()) {
5874 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5875 llvm::Value *NumThreads =
5876 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5877 /*IgnoreResultAssign*/ true);
5878 NumThreadsVal =
5879 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5880 }
5881
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005882 // Select the lesser of thread_limit and num_threads.
5883 if (NumThreadsVal)
5884 ThreadLimitVal = ThreadLimitVal
5885 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5886 ThreadLimitVal),
5887 NumThreadsVal, ThreadLimitVal)
5888 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005889
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005890 // Set default value passed to the runtime if either teams or a target
5891 // parallel type directive is found but no clause is specified.
5892 if (!ThreadLimitVal)
5893 ThreadLimitVal = DefaultThreadLimitVal;
5894
5895 return ThreadLimitVal;
5896 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005897
Samuel Antaob68e2db2016-03-03 16:20:23 +00005898 // If the current target region has a teams region enclosed, we need to get
5899 // the thread limit to pass to the runtime function call. This is done
5900 // by generating the expression in a inlined region. This is required because
5901 // the expression is captured in the enclosing target environment when the
5902 // teams directive is not combined with target.
5903
5904 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5905
5906 // FIXME: Accommodate other combined directives with teams when they become
5907 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005908 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5909 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005910 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5911 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5912 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5913 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5914 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5915 /*IsSigned=*/true);
5916 }
5917
5918 // If we have an enclosed teams directive but no thread_limit clause we use
5919 // the default value 0.
5920 return CGF.Builder.getInt32(0);
5921 }
5922
5923 // No teams associated with the directive.
5924 return nullptr;
5925}
5926
Samuel Antao86ace552016-04-27 22:40:57 +00005927namespace {
5928// \brief Utility to handle information from clauses associated with a given
5929// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5930// It provides a convenient interface to obtain the information and generate
5931// code for that information.
5932class MappableExprsHandler {
5933public:
5934 /// \brief Values for bit flags used to specify the mapping type for
5935 /// offloading.
5936 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005937 /// \brief Allocate memory on the device and move data from host to device.
5938 OMP_MAP_TO = 0x01,
5939 /// \brief Allocate memory on the device and move data from device to host.
5940 OMP_MAP_FROM = 0x02,
5941 /// \brief Always perform the requested mapping action on the element, even
5942 /// if it was already mapped before.
5943 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005944 /// \brief Delete the element from the device environment, ignoring the
5945 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005946 OMP_MAP_DELETE = 0x08,
5947 /// \brief The element being mapped is a pointer, therefore the pointee
5948 /// should be mapped as well.
5949 OMP_MAP_IS_PTR = 0x10,
5950 /// \brief This flags signals that an argument is the first one relating to
5951 /// a map/private clause expression. For some cases a single
5952 /// map/privatization results in multiple arguments passed to the runtime
5953 /// library.
5954 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005955 /// \brief Signal that the runtime library has to return the device pointer
5956 /// in the current position for the data being mapped.
5957 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005958 /// \brief This flag signals that the reference being passed is a pointer to
5959 /// private data.
5960 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005961 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005962 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005963 };
5964
Samuel Antaocc10b852016-07-28 14:23:26 +00005965 /// Class that associates information with a base pointer to be passed to the
5966 /// runtime library.
5967 class BasePointerInfo {
5968 /// The base pointer.
5969 llvm::Value *Ptr = nullptr;
5970 /// The base declaration that refers to this device pointer, or null if
5971 /// there is none.
5972 const ValueDecl *DevPtrDecl = nullptr;
5973
5974 public:
5975 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5976 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5977 llvm::Value *operator*() const { return Ptr; }
5978 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5979 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5980 };
5981
5982 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005983 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5984 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5985
5986private:
5987 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005988 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005989
5990 /// \brief Function the directive is being generated for.
5991 CodeGenFunction &CGF;
5992
Samuel Antaod486f842016-05-26 16:53:38 +00005993 /// \brief Set of all first private variables in the current directive.
5994 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5995
Samuel Antao6890b092016-07-28 14:25:09 +00005996 /// Map between device pointer declarations and their expression components.
5997 /// The key value for declarations in 'this' is null.
5998 llvm::DenseMap<
5999 const ValueDecl *,
6000 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6001 DevPointersMap;
6002
Samuel Antao86ace552016-04-27 22:40:57 +00006003 llvm::Value *getExprTypeSize(const Expr *E) const {
6004 auto ExprTy = E->getType().getCanonicalType();
6005
6006 // Reference types are ignored for mapping purposes.
6007 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6008 ExprTy = RefTy->getPointeeType().getCanonicalType();
6009
6010 // Given that an array section is considered a built-in type, we need to
6011 // do the calculation based on the length of the section instead of relying
6012 // on CGF.getTypeSize(E->getType()).
6013 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6014 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6015 OAE->getBase()->IgnoreParenImpCasts())
6016 .getCanonicalType();
6017
6018 // If there is no length associated with the expression, that means we
6019 // are using the whole length of the base.
6020 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6021 return CGF.getTypeSize(BaseTy);
6022
6023 llvm::Value *ElemSize;
6024 if (auto *PTy = BaseTy->getAs<PointerType>())
6025 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6026 else {
6027 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6028 assert(ATy && "Expecting array type if not a pointer type.");
6029 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6030 }
6031
6032 // If we don't have a length at this point, that is because we have an
6033 // array section with a single element.
6034 if (!OAE->getLength())
6035 return ElemSize;
6036
6037 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6038 LengthVal =
6039 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6040 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6041 }
6042 return CGF.getTypeSize(ExprTy);
6043 }
6044
6045 /// \brief Return the corresponding bits for a given map clause modifier. Add
6046 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006047 /// map as the first one of a series of maps that relate to the same map
6048 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00006049 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6050 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00006051 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006052 unsigned Bits = 0u;
6053 switch (MapType) {
6054 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006055 case OMPC_MAP_release:
6056 // alloc and release is the default behavior in the runtime library, i.e.
6057 // if we don't pass any bits alloc/release that is what the runtime is
6058 // going to do. Therefore, we don't need to signal anything for these two
6059 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006060 break;
6061 case OMPC_MAP_to:
6062 Bits = OMP_MAP_TO;
6063 break;
6064 case OMPC_MAP_from:
6065 Bits = OMP_MAP_FROM;
6066 break;
6067 case OMPC_MAP_tofrom:
6068 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6069 break;
6070 case OMPC_MAP_delete:
6071 Bits = OMP_MAP_DELETE;
6072 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006073 default:
6074 llvm_unreachable("Unexpected map type!");
6075 break;
6076 }
6077 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00006078 Bits |= OMP_MAP_IS_PTR;
6079 if (AddIsFirstFlag)
6080 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00006081 if (MapTypeModifier == OMPC_MAP_always)
6082 Bits |= OMP_MAP_ALWAYS;
6083 return Bits;
6084 }
6085
6086 /// \brief Return true if the provided expression is a final array section. A
6087 /// final array section, is one whose length can't be proved to be one.
6088 bool isFinalArraySectionExpression(const Expr *E) const {
6089 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6090
6091 // It is not an array section and therefore not a unity-size one.
6092 if (!OASE)
6093 return false;
6094
6095 // An array section with no colon always refer to a single element.
6096 if (OASE->getColonLoc().isInvalid())
6097 return false;
6098
6099 auto *Length = OASE->getLength();
6100
6101 // If we don't have a length we have to check if the array has size 1
6102 // for this dimension. Also, we should always expect a length if the
6103 // base type is pointer.
6104 if (!Length) {
6105 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6106 OASE->getBase()->IgnoreParenImpCasts())
6107 .getCanonicalType();
6108 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6109 return ATy->getSize().getSExtValue() != 1;
6110 // If we don't have a constant dimension length, we have to consider
6111 // the current section as having any size, so it is not necessarily
6112 // unitary. If it happen to be unity size, that's user fault.
6113 return true;
6114 }
6115
6116 // Check if the length evaluates to 1.
6117 llvm::APSInt ConstLength;
6118 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6119 return true; // Can have more that size 1.
6120
6121 return ConstLength.getSExtValue() != 1;
6122 }
6123
6124 /// \brief Generate the base pointers, section pointers, sizes and map type
6125 /// bits for the provided map type, map modifier, and expression components.
6126 /// \a IsFirstComponent should be set to true if the provided set of
6127 /// components is the first associated with a capture.
6128 void generateInfoForComponentList(
6129 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6130 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006131 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006132 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
6133 bool IsFirstComponentList) const {
6134
6135 // The following summarizes what has to be generated for each map and the
6136 // types bellow. The generated information is expressed in this order:
6137 // base pointer, section pointer, size, flags
6138 // (to add to the ones that come from the map type and modifier).
6139 //
6140 // double d;
6141 // int i[100];
6142 // float *p;
6143 //
6144 // struct S1 {
6145 // int i;
6146 // float f[50];
6147 // }
6148 // struct S2 {
6149 // int i;
6150 // float f[50];
6151 // S1 s;
6152 // double *p;
6153 // struct S2 *ps;
6154 // }
6155 // S2 s;
6156 // S2 *ps;
6157 //
6158 // map(d)
6159 // &d, &d, sizeof(double), noflags
6160 //
6161 // map(i)
6162 // &i, &i, 100*sizeof(int), noflags
6163 //
6164 // map(i[1:23])
6165 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6166 //
6167 // map(p)
6168 // &p, &p, sizeof(float*), noflags
6169 //
6170 // map(p[1:24])
6171 // p, &p[1], 24*sizeof(float), noflags
6172 //
6173 // map(s)
6174 // &s, &s, sizeof(S2), noflags
6175 //
6176 // map(s.i)
6177 // &s, &(s.i), sizeof(int), noflags
6178 //
6179 // map(s.s.f)
6180 // &s, &(s.i.f), 50*sizeof(int), noflags
6181 //
6182 // map(s.p)
6183 // &s, &(s.p), sizeof(double*), noflags
6184 //
6185 // map(s.p[:22], s.a s.b)
6186 // &s, &(s.p), sizeof(double*), noflags
6187 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
6188 //
6189 // map(s.ps)
6190 // &s, &(s.ps), sizeof(S2*), noflags
6191 //
6192 // map(s.ps->s.i)
6193 // &s, &(s.ps), sizeof(S2*), noflags
6194 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
6195 //
6196 // map(s.ps->ps)
6197 // &s, &(s.ps), sizeof(S2*), noflags
6198 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6199 //
6200 // map(s.ps->ps->ps)
6201 // &s, &(s.ps), sizeof(S2*), noflags
6202 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6203 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6204 //
6205 // map(s.ps->ps->s.f[:22])
6206 // &s, &(s.ps), sizeof(S2*), noflags
6207 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6208 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
6209 //
6210 // map(ps)
6211 // &ps, &ps, sizeof(S2*), noflags
6212 //
6213 // map(ps->i)
6214 // ps, &(ps->i), sizeof(int), noflags
6215 //
6216 // map(ps->s.f)
6217 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6218 //
6219 // map(ps->p)
6220 // ps, &(ps->p), sizeof(double*), noflags
6221 //
6222 // map(ps->p[:22])
6223 // ps, &(ps->p), sizeof(double*), noflags
6224 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
6225 //
6226 // map(ps->ps)
6227 // ps, &(ps->ps), sizeof(S2*), noflags
6228 //
6229 // map(ps->ps->s.i)
6230 // ps, &(ps->ps), sizeof(S2*), noflags
6231 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
6232 //
6233 // map(ps->ps->ps)
6234 // ps, &(ps->ps), sizeof(S2*), noflags
6235 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6236 //
6237 // map(ps->ps->ps->ps)
6238 // ps, &(ps->ps), sizeof(S2*), noflags
6239 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6240 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6241 //
6242 // map(ps->ps->ps->s.f[:22])
6243 // ps, &(ps->ps), sizeof(S2*), noflags
6244 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6245 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
6246 // extra_flag
6247
6248 // Track if the map information being generated is the first for a capture.
6249 bool IsCaptureFirstInfo = IsFirstComponentList;
6250
6251 // Scan the components from the base to the complete expression.
6252 auto CI = Components.rbegin();
6253 auto CE = Components.rend();
6254 auto I = CI;
6255
6256 // Track if the map information being generated is the first for a list of
6257 // components.
6258 bool IsExpressionFirstInfo = true;
6259 llvm::Value *BP = nullptr;
6260
6261 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6262 // The base is the 'this' pointer. The content of the pointer is going
6263 // to be the base of the field being mapped.
6264 BP = CGF.EmitScalarExpr(ME->getBase());
6265 } else {
6266 // The base is the reference to the variable.
6267 // BP = &Var.
6268 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
6269 .getPointer();
6270
6271 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006272 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006273 // reference. References are ignored for mapping purposes.
6274 QualType Ty =
6275 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6276 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6277 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006278 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006279 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006280 .getPointer();
6281
6282 // We do not need to generate individual map information for the
6283 // pointer, it can be associated with the combined storage.
6284 ++I;
6285 }
6286 }
6287
6288 for (; I != CE; ++I) {
6289 auto Next = std::next(I);
6290
6291 // We need to generate the addresses and sizes if this is the last
6292 // component, if the component is a pointer or if it is an array section
6293 // whose length can't be proved to be one. If this is a pointer, it
6294 // becomes the base address for the following components.
6295
6296 // A final array section, is one whose length can't be proved to be one.
6297 bool IsFinalArraySection =
6298 isFinalArraySectionExpression(I->getAssociatedExpression());
6299
6300 // Get information on whether the element is a pointer. Have to do a
6301 // special treatment for array sections given that they are built-in
6302 // types.
6303 const auto *OASE =
6304 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6305 bool IsPointer =
6306 (OASE &&
6307 OMPArraySectionExpr::getBaseOriginalType(OASE)
6308 .getCanonicalType()
6309 ->isAnyPointerType()) ||
6310 I->getAssociatedExpression()->getType()->isAnyPointerType();
6311
6312 if (Next == CE || IsPointer || IsFinalArraySection) {
6313
6314 // If this is not the last component, we expect the pointer to be
6315 // associated with an array expression or member expression.
6316 assert((Next == CE ||
6317 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6318 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6319 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6320 "Unexpected expression");
6321
Samuel Antao86ace552016-04-27 22:40:57 +00006322 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
6323 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6324
Samuel Antao03a3cec2016-07-27 22:52:16 +00006325 // If we have a member expression and the current component is a
6326 // reference, we have to map the reference too. Whenever we have a
6327 // reference, the section that reference refers to is going to be a
6328 // load instruction from the storage assigned to the reference.
6329 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6330 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6331 auto *LI = cast<llvm::LoadInst>(LB);
6332 auto *RefAddr = LI->getPointerOperand();
6333
6334 BasePointers.push_back(BP);
6335 Pointers.push_back(RefAddr);
6336 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6337 Types.push_back(getMapTypeBits(
6338 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
6339 !IsExpressionFirstInfo, IsCaptureFirstInfo));
6340 IsExpressionFirstInfo = false;
6341 IsCaptureFirstInfo = false;
6342 // The reference will be the next base address.
6343 BP = RefAddr;
6344 }
6345
6346 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006347 Pointers.push_back(LB);
6348 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006349
Samuel Antao6782e942016-05-26 16:48:10 +00006350 // We need to add a pointer flag for each map that comes from the
6351 // same expression except for the first one. We also need to signal
6352 // this map is the first one that relates with the current capture
6353 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00006354 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
6355 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00006356 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006357
6358 // If we have a final array section, we are done with this expression.
6359 if (IsFinalArraySection)
6360 break;
6361
6362 // The pointer becomes the base for the next element.
6363 if (Next != CE)
6364 BP = LB;
6365
6366 IsExpressionFirstInfo = false;
6367 IsCaptureFirstInfo = false;
6368 continue;
6369 }
6370 }
6371 }
6372
Samuel Antaod486f842016-05-26 16:53:38 +00006373 /// \brief Return the adjusted map modifiers if the declaration a capture
6374 /// refers to appears in a first-private clause. This is expected to be used
6375 /// only with directives that start with 'target'.
6376 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6377 unsigned CurrentModifiers) {
6378 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6379
6380 // A first private variable captured by reference will use only the
6381 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6382 // declaration is known as first-private in this handler.
6383 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6384 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
6385 MappableExprsHandler::OMP_MAP_TO;
6386
6387 // We didn't modify anything.
6388 return CurrentModifiers;
6389 }
6390
Samuel Antao86ace552016-04-27 22:40:57 +00006391public:
6392 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006393 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006394 // Extract firstprivate clause information.
6395 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6396 for (const auto *D : C->varlists())
6397 FirstPrivateDecls.insert(
6398 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006399 // Extract device pointer clause information.
6400 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6401 for (auto L : C->component_lists())
6402 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006403 }
Samuel Antao86ace552016-04-27 22:40:57 +00006404
6405 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006406 /// types for the extracted mappable expressions. Also, for each item that
6407 /// relates with a device pointer, a pair of the relevant declaration and
6408 /// index where it occurs is appended to the device pointers info array.
6409 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006410 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6411 MapFlagsArrayTy &Types) const {
6412 BasePointers.clear();
6413 Pointers.clear();
6414 Sizes.clear();
6415 Types.clear();
6416
6417 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006418 /// Kind that defines how a device pointer has to be returned.
6419 enum ReturnPointerKind {
6420 // Don't have to return any pointer.
6421 RPK_None,
6422 // Pointer is the base of the declaration.
6423 RPK_Base,
6424 // Pointer is a member of the base declaration - 'this'
6425 RPK_Member,
6426 // Pointer is a reference and a member of the base declaration - 'this'
6427 RPK_MemberReference,
6428 };
Samuel Antao86ace552016-04-27 22:40:57 +00006429 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006430 OpenMPMapClauseKind MapType;
6431 OpenMPMapClauseKind MapTypeModifier;
6432 ReturnPointerKind ReturnDevicePointer;
6433
6434 MapInfo()
6435 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
6436 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00006437 MapInfo(
6438 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6439 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6440 ReturnPointerKind ReturnDevicePointer)
6441 : Components(Components), MapType(MapType),
6442 MapTypeModifier(MapTypeModifier),
6443 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006444 };
6445
6446 // We have to process the component lists that relate with the same
6447 // declaration in a single chunk so that we can generate the map flags
6448 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006449 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006450
6451 // Helper function to fill the information map for the different supported
6452 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006453 auto &&InfoGen = [&Info](
6454 const ValueDecl *D,
6455 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6456 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006457 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006458 const ValueDecl *VD =
6459 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
6460 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
6461 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006462
Paul Robinson78fb1322016-08-01 22:12:46 +00006463 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006464 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006465 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006466 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
6467 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006468 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006469 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006470 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
6471 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006472 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006473 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006474 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
6475 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00006476
Samuel Antaocc10b852016-07-28 14:23:26 +00006477 // Look at the use_device_ptr clause information and mark the existing map
6478 // entries as such. If there is no map information for an entry in the
6479 // use_device_ptr list, we create one with map type 'alloc' and zero size
6480 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006481 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006482 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006483 for (auto L : C->component_lists()) {
6484 assert(!L.second.empty() && "Not expecting empty list of components!");
6485 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6486 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6487 auto *IE = L.second.back().getAssociatedExpression();
6488 // If the first component is a member expression, we have to look into
6489 // 'this', which maps to null in the map of map information. Otherwise
6490 // look directly for the information.
6491 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6492
6493 // We potentially have map information for this declaration already.
6494 // Look for the first set of components that refer to it.
6495 if (It != Info.end()) {
6496 auto CI = std::find_if(
6497 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6498 return MI.Components.back().getAssociatedDeclaration() == VD;
6499 });
6500 // If we found a map entry, signal that the pointer has to be returned
6501 // and move on to the next declaration.
6502 if (CI != It->second.end()) {
6503 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6504 ? (VD->getType()->isReferenceType()
6505 ? MapInfo::RPK_MemberReference
6506 : MapInfo::RPK_Member)
6507 : MapInfo::RPK_Base;
6508 continue;
6509 }
6510 }
6511
6512 // We didn't find any match in our map information - generate a zero
6513 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006514 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006515 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006516 this->CGF
6517 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006518 .getScalarVal();
6519 BasePointers.push_back({Ptr, VD});
6520 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006521 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00006522 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6523 }
6524
Samuel Antao86ace552016-04-27 22:40:57 +00006525 for (auto &M : Info) {
6526 // We need to know when we generate information for the first component
6527 // associated with a capture, because the mapping flags depend on it.
6528 bool IsFirstComponentList = true;
6529 for (MapInfo &L : M.second) {
6530 assert(!L.Components.empty() &&
6531 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006532
6533 // Remember the current base pointer index.
6534 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006535 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00006536 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
6537 L.Components, BasePointers, Pointers,
6538 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00006539
6540 // If this entry relates with a device pointer, set the relevant
6541 // declaration and add the 'return pointer' flag.
6542 if (IsFirstComponentList &&
6543 L.ReturnDevicePointer != MapInfo::RPK_None) {
6544 // If the pointer is not the base of the map, we need to skip the
6545 // base. If it is a reference in a member field, we also need to skip
6546 // the map of the reference.
6547 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6548 ++CurrentBasePointersIdx;
6549 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6550 ++CurrentBasePointersIdx;
6551 }
6552 assert(BasePointers.size() > CurrentBasePointersIdx &&
6553 "Unexpected number of mapped base pointers.");
6554
6555 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6556 assert(RelevantVD &&
6557 "No relevant declaration related with device pointer??");
6558
6559 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6560 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6561 }
Samuel Antao86ace552016-04-27 22:40:57 +00006562 IsFirstComponentList = false;
6563 }
6564 }
6565 }
6566
6567 /// \brief Generate the base pointers, section pointers, sizes and map types
6568 /// associated to a given capture.
6569 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006570 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006571 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006572 MapValuesArrayTy &Pointers,
6573 MapValuesArrayTy &Sizes,
6574 MapFlagsArrayTy &Types) const {
6575 assert(!Cap->capturesVariableArrayType() &&
6576 "Not expecting to generate map info for a variable array type!");
6577
6578 BasePointers.clear();
6579 Pointers.clear();
6580 Sizes.clear();
6581 Types.clear();
6582
Samuel Antao6890b092016-07-28 14:25:09 +00006583 // We need to know when we generating information for the first component
6584 // associated with a capture, because the mapping flags depend on it.
6585 bool IsFirstComponentList = true;
6586
Samuel Antao86ace552016-04-27 22:40:57 +00006587 const ValueDecl *VD =
6588 Cap->capturesThis()
6589 ? nullptr
6590 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6591
Samuel Antao6890b092016-07-28 14:25:09 +00006592 // If this declaration appears in a is_device_ptr clause we just have to
6593 // pass the pointer by value. If it is a reference to a declaration, we just
6594 // pass its value, otherwise, if it is a member expression, we need to map
6595 // 'to' the field.
6596 if (!VD) {
6597 auto It = DevPointersMap.find(VD);
6598 if (It != DevPointersMap.end()) {
6599 for (auto L : It->second) {
6600 generateInfoForComponentList(
6601 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
6602 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
6603 IsFirstComponentList = false;
6604 }
6605 return;
6606 }
6607 } else if (DevPointersMap.count(VD)) {
6608 BasePointers.push_back({Arg, VD});
6609 Pointers.push_back(Arg);
6610 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6611 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6612 return;
6613 }
6614
Paul Robinson78fb1322016-08-01 22:12:46 +00006615 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006616 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006617 for (auto L : C->decl_component_lists(VD)) {
6618 assert(L.first == VD &&
6619 "We got information for the wrong declaration??");
6620 assert(!L.second.empty() &&
6621 "Not expecting declaration with no component lists.");
6622 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
6623 L.second, BasePointers, Pointers, Sizes,
6624 Types, IsFirstComponentList);
6625 IsFirstComponentList = false;
6626 }
6627
6628 return;
6629 }
Samuel Antaod486f842016-05-26 16:53:38 +00006630
6631 /// \brief Generate the default map information for a given capture \a CI,
6632 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006633 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6634 const FieldDecl &RI, llvm::Value *CV,
6635 MapBaseValuesArrayTy &CurBasePointers,
6636 MapValuesArrayTy &CurPointers,
6637 MapValuesArrayTy &CurSizes,
6638 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006639
6640 // Do the default mapping.
6641 if (CI.capturesThis()) {
6642 CurBasePointers.push_back(CV);
6643 CurPointers.push_back(CV);
6644 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6645 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6646 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006647 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006648 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006649 CurBasePointers.push_back(CV);
6650 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006651 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006652 // We have to signal to the runtime captures passed by value that are
6653 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00006654 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006655 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6656 } else {
6657 // Pointers are implicitly mapped with a zero size and no flags
6658 // (other than first map that is added for all implicit maps).
6659 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006660 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6661 }
6662 } else {
6663 assert(CI.capturesVariable() && "Expected captured reference.");
6664 CurBasePointers.push_back(CV);
6665 CurPointers.push_back(CV);
6666
6667 const ReferenceType *PtrTy =
6668 cast<ReferenceType>(RI.getType().getTypePtr());
6669 QualType ElementType = PtrTy->getPointeeType();
6670 CurSizes.push_back(CGF.getTypeSize(ElementType));
6671 // The default map type for a scalar/complex type is 'to' because by
6672 // default the value doesn't have to be retrieved. For an aggregate
6673 // type, the default is 'tofrom'.
6674 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006675 ? (OMP_MAP_TO | OMP_MAP_FROM)
6676 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006677
6678 // If we have a capture by reference we may need to add the private
6679 // pointer flag if the base declaration shows in some first-private
6680 // clause.
6681 CurMapTypes.back() =
6682 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6683 }
6684 // Every default map produces a single argument, so, it is always the
6685 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00006686 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00006687 }
Samuel Antao86ace552016-04-27 22:40:57 +00006688};
Samuel Antaodf158d52016-04-27 22:58:19 +00006689
6690enum OpenMPOffloadingReservedDeviceIDs {
6691 /// \brief Device ID if the device was not defined, runtime should get it
6692 /// from environment variables in the spec.
6693 OMP_DEVICEID_UNDEF = -1,
6694};
6695} // anonymous namespace
6696
6697/// \brief Emit the arrays used to pass the captures and map information to the
6698/// offloading runtime library. If there is no map or capture information,
6699/// return nullptr by reference.
6700static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006701emitOffloadingArrays(CodeGenFunction &CGF,
6702 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006703 MappableExprsHandler::MapValuesArrayTy &Pointers,
6704 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006705 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6706 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006707 auto &CGM = CGF.CGM;
6708 auto &Ctx = CGF.getContext();
6709
Samuel Antaocc10b852016-07-28 14:23:26 +00006710 // Reset the array information.
6711 Info.clearArrayInfo();
6712 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006713
Samuel Antaocc10b852016-07-28 14:23:26 +00006714 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006715 // Detect if we have any capture size requiring runtime evaluation of the
6716 // size so that a constant array could be eventually used.
6717 bool hasRuntimeEvaluationCaptureSize = false;
6718 for (auto *S : Sizes)
6719 if (!isa<llvm::Constant>(S)) {
6720 hasRuntimeEvaluationCaptureSize = true;
6721 break;
6722 }
6723
Samuel Antaocc10b852016-07-28 14:23:26 +00006724 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006725 QualType PointerArrayType =
6726 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6727 /*IndexTypeQuals=*/0);
6728
Samuel Antaocc10b852016-07-28 14:23:26 +00006729 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006730 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006731 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006732 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6733
6734 // If we don't have any VLA types or other types that require runtime
6735 // evaluation, we can use a constant array for the map sizes, otherwise we
6736 // need to fill up the arrays as we do for the pointers.
6737 if (hasRuntimeEvaluationCaptureSize) {
6738 QualType SizeArrayType = Ctx.getConstantArrayType(
6739 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6740 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006741 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006742 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6743 } else {
6744 // We expect all the sizes to be constant, so we collect them to create
6745 // a constant array.
6746 SmallVector<llvm::Constant *, 16> ConstSizes;
6747 for (auto S : Sizes)
6748 ConstSizes.push_back(cast<llvm::Constant>(S));
6749
6750 auto *SizesArrayInit = llvm::ConstantArray::get(
6751 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6752 auto *SizesArrayGbl = new llvm::GlobalVariable(
6753 CGM.getModule(), SizesArrayInit->getType(),
6754 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6755 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006756 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006757 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006758 }
6759
6760 // The map types are always constant so we don't need to generate code to
6761 // fill arrays. Instead, we create an array constant.
6762 llvm::Constant *MapTypesArrayInit =
6763 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6764 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6765 CGM.getModule(), MapTypesArrayInit->getType(),
6766 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6767 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006768 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006769 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006770
Samuel Antaocc10b852016-07-28 14:23:26 +00006771 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6772 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006773 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006774 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6775 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006776 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6777 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006778 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6779 CGF.Builder.CreateStore(BPVal, BPAddr);
6780
Samuel Antaocc10b852016-07-28 14:23:26 +00006781 if (Info.requiresDevicePointerInfo())
6782 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6783 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6784
Samuel Antaodf158d52016-04-27 22:58:19 +00006785 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006786 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006787 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6788 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006789 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6790 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006791 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6792 CGF.Builder.CreateStore(PVal, PAddr);
6793
6794 if (hasRuntimeEvaluationCaptureSize) {
6795 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006796 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6797 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006798 /*Idx0=*/0,
6799 /*Idx1=*/i);
6800 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6801 CGF.Builder.CreateStore(
6802 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6803 SAddr);
6804 }
6805 }
6806 }
6807}
6808/// \brief Emit the arguments to be passed to the runtime library based on the
6809/// arrays of pointers, sizes and map types.
6810static void emitOffloadingArraysArgument(
6811 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6812 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006813 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006814 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006815 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006816 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006817 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6818 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006819 /*Idx0=*/0, /*Idx1=*/0);
6820 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006821 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6822 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006823 /*Idx0=*/0,
6824 /*Idx1=*/0);
6825 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006826 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006827 /*Idx0=*/0, /*Idx1=*/0);
6828 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006829 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6830 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006831 /*Idx0=*/0,
6832 /*Idx1=*/0);
6833 } else {
6834 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6835 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6836 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6837 MapTypesArrayArg =
6838 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6839 }
Samuel Antao86ace552016-04-27 22:40:57 +00006840}
6841
Samuel Antaobed3c462015-10-02 16:14:20 +00006842void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6843 const OMPExecutableDirective &D,
6844 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006845 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006846 const Expr *IfCond, const Expr *Device,
6847 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006848 if (!CGF.HaveInsertPoint())
6849 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006850
Samuel Antaoee8fb302016-01-06 13:42:12 +00006851 assert(OutlinedFn && "Invalid outlined function!");
6852
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006853 auto &Ctx = CGF.getContext();
6854
Samuel Antao86ace552016-04-27 22:40:57 +00006855 // Fill up the arrays with all the captured variables.
6856 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006857 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006858 MappableExprsHandler::MapValuesArrayTy Pointers;
6859 MappableExprsHandler::MapValuesArrayTy Sizes;
6860 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006861
Samuel Antaocc10b852016-07-28 14:23:26 +00006862 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006863 MappableExprsHandler::MapValuesArrayTy CurPointers;
6864 MappableExprsHandler::MapValuesArrayTy CurSizes;
6865 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6866
Samuel Antaod486f842016-05-26 16:53:38 +00006867 // Get mappable expression information.
6868 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006869
6870 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6871 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006872 auto CV = CapturedVars.begin();
6873 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6874 CE = CS.capture_end();
6875 CI != CE; ++CI, ++RI, ++CV) {
6876 StringRef Name;
6877 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00006878
Samuel Antao86ace552016-04-27 22:40:57 +00006879 CurBasePointers.clear();
6880 CurPointers.clear();
6881 CurSizes.clear();
6882 CurMapTypes.clear();
6883
6884 // VLA sizes are passed to the outlined region by copy and do not have map
6885 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006886 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006887 CurBasePointers.push_back(*CV);
6888 CurPointers.push_back(*CV);
6889 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006890 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006891 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6892 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006893 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006894 // If we have any information in the map clause, we use it, otherwise we
6895 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006896 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006897 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006898 if (CurBasePointers.empty())
6899 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6900 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006901 }
Samuel Antao86ace552016-04-27 22:40:57 +00006902 // We expect to have at least an element of information for this capture.
6903 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6904 assert(CurBasePointers.size() == CurPointers.size() &&
6905 CurBasePointers.size() == CurSizes.size() &&
6906 CurBasePointers.size() == CurMapTypes.size() &&
6907 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006908
Samuel Antao86ace552016-04-27 22:40:57 +00006909 // The kernel args are always the first elements of the base pointers
6910 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006911 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006912 // We need to append the results of this capture to what we already have.
6913 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6914 Pointers.append(CurPointers.begin(), CurPointers.end());
6915 Sizes.append(CurSizes.begin(), CurSizes.end());
6916 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006917 }
6918
6919 // Keep track on whether the host function has to be executed.
6920 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006921 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006922 auto OffloadError = CGF.MakeAddrLValue(
6923 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6924 OffloadErrorQType);
6925 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6926 OffloadError);
6927
6928 // Fill up the pointer arrays and transfer execution to the device.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006929 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6930 OutlinedFnID, OffloadError,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006931 &D](CodeGenFunction &CGF, PrePostActionTy &) {
6932 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006933 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006934 TargetDataInfo Info;
6935 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6936 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6937 Info.PointersArray, Info.SizesArray,
6938 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006939
6940 // On top of the arrays that were filled up, the target offloading call
6941 // takes as arguments the device id as well as the host pointer. The host
6942 // pointer is used by the runtime library to identify the current target
6943 // region, so it only has to be unique and not necessarily point to
6944 // anything. It could be the pointer to the outlined function that
6945 // implements the target region, but we aren't using that so that the
6946 // compiler doesn't need to keep that, and could therefore inline the host
6947 // function if proven worthwhile during optimization.
6948
Samuel Antaoee8fb302016-01-06 13:42:12 +00006949 // From this point on, we need to have an ID of the target region defined.
6950 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006951
6952 // Emit device ID if any.
6953 llvm::Value *DeviceID;
6954 if (Device)
6955 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006956 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006957 else
6958 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6959
Samuel Antaodf158d52016-04-27 22:58:19 +00006960 // Emit the number of elements in the offloading arrays.
6961 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6962
Samuel Antaob68e2db2016-03-03 16:20:23 +00006963 // Return value of the runtime offloading call.
6964 llvm::Value *Return;
6965
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006966 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6967 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006968
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006969 // The target region is an outlined function launched by the runtime
6970 // via calls __tgt_target() or __tgt_target_teams().
6971 //
6972 // __tgt_target() launches a target region with one team and one thread,
6973 // executing a serial region. This master thread may in turn launch
6974 // more threads within its team upon encountering a parallel region,
6975 // however, no additional teams can be launched on the device.
6976 //
6977 // __tgt_target_teams() launches a target region with one or more teams,
6978 // each with one or more threads. This call is required for target
6979 // constructs such as:
6980 // 'target teams'
6981 // 'target' / 'teams'
6982 // 'target teams distribute parallel for'
6983 // 'target parallel'
6984 // and so on.
6985 //
6986 // Note that on the host and CPU targets, the runtime implementation of
6987 // these calls simply call the outlined function without forking threads.
6988 // The outlined functions themselves have runtime calls to
6989 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
6990 // the compiler in emitTeamsCall() and emitParallelCall().
6991 //
6992 // In contrast, on the NVPTX target, the implementation of
6993 // __tgt_target_teams() launches a GPU kernel with the requested number
6994 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006995 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006996 // If we have NumTeams defined this means that we have an enclosed teams
6997 // region. Therefore we also expect to have NumThreads defined. These two
6998 // values should be defined in the presence of a teams directive,
6999 // regardless of having any clauses associated. If the user is using teams
7000 // but no clauses, these two values will be the default that should be
7001 // passed to the runtime library - a 32-bit integer with the value zero.
7002 assert(NumThreads && "Thread limit expression should be available along "
7003 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007004 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007005 DeviceID, OutlinedFnID,
7006 PointerNum, Info.BasePointersArray,
7007 Info.PointersArray, Info.SizesArray,
7008 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007009 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007010 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007011 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007012 } else {
7013 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007014 DeviceID, OutlinedFnID,
7015 PointerNum, Info.BasePointersArray,
7016 Info.PointersArray, Info.SizesArray,
7017 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007018 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007019 OffloadingArgs);
7020 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007021
7022 CGF.EmitStoreOfScalar(Return, OffloadError);
7023 };
7024
Samuel Antaoee8fb302016-01-06 13:42:12 +00007025 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007026 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
7027 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00007028 OffloadError);
7029 };
7030
7031 // If we have a target function ID it means that we need to support
7032 // offloading, otherwise, just execute on the host. We need to execute on host
7033 // regardless of the conditional in the if clause if, e.g., the user do not
7034 // specify target triples.
7035 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007036 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007037 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007038 else {
7039 RegionCodeGenTy ThenRCG(ThenGen);
7040 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007041 }
7042 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007043 RegionCodeGenTy ElseRCG(ElseGen);
7044 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007045 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007046
7047 // Check the error code and execute the host version if required.
7048 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
7049 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
7050 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
7051 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
7052 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7053
7054 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev3c595a62017-08-14 15:01:03 +00007055 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00007056 CGF.EmitBranch(OffloadContBlock);
7057
7058 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007059}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007060
7061void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7062 StringRef ParentName) {
7063 if (!S)
7064 return;
7065
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007066 // Codegen OMP target directives that offload compute to the device.
7067 bool requiresDeviceCodegen =
7068 isa<OMPExecutableDirective>(S) &&
7069 isOpenMPTargetExecutionDirective(
7070 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007071
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007072 if (requiresDeviceCodegen) {
7073 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007074 unsigned DeviceID;
7075 unsigned FileID;
7076 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007077 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007078 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007079
7080 // Is this a target region that should not be emitted as an entry point? If
7081 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007082 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7083 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007084 return;
7085
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007086 switch (S->getStmtClass()) {
7087 case Stmt::OMPTargetDirectiveClass:
7088 CodeGenFunction::EmitOMPTargetDeviceFunction(
7089 CGM, ParentName, cast<OMPTargetDirective>(*S));
7090 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007091 case Stmt::OMPTargetParallelDirectiveClass:
7092 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7093 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7094 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007095 case Stmt::OMPTargetTeamsDirectiveClass:
7096 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7097 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7098 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007099 default:
7100 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7101 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007102 return;
7103 }
7104
7105 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007106 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007107 return;
7108
7109 scanForTargetRegionsFunctions(
7110 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7111 ParentName);
7112 return;
7113 }
7114
7115 // If this is a lambda function, look into its body.
7116 if (auto *L = dyn_cast<LambdaExpr>(S))
7117 S = L->getBody();
7118
7119 // Keep looking for target regions recursively.
7120 for (auto *II : S->children())
7121 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007122}
7123
7124bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7125 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7126
7127 // If emitting code for the host, we do not process FD here. Instead we do
7128 // the normal code generation.
7129 if (!CGM.getLangOpts().OpenMPIsDevice)
7130 return false;
7131
7132 // Try to detect target regions in the function.
7133 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7134
Samuel Antao4b75b872016-12-12 19:26:31 +00007135 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007136 // scanning. Therefore, we signal that this function is completely dealt
7137 // with.
7138 return true;
7139}
7140
7141bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7142 if (!CGM.getLangOpts().OpenMPIsDevice)
7143 return false;
7144
7145 // Check if there are Ctors/Dtors in this declaration and look for target
7146 // regions in it. We use the complete variant to produce the kernel name
7147 // mangling.
7148 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7149 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7150 for (auto *Ctor : RD->ctors()) {
7151 StringRef ParentName =
7152 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7153 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7154 }
7155 auto *Dtor = RD->getDestructor();
7156 if (Dtor) {
7157 StringRef ParentName =
7158 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7159 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7160 }
7161 }
7162
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007163 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007164 // implemented yet). Therefore we signal that GD was processed in this case.
7165 return true;
7166}
7167
7168bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7169 auto *VD = GD.getDecl();
7170 if (isa<FunctionDecl>(VD))
7171 return emitTargetFunctions(GD);
7172
7173 return emitTargetGlobalVariable(GD);
7174}
7175
7176llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7177 // If we have offloading in the current module, we need to emit the entries
7178 // now and register the offloading descriptor.
7179 createOffloadEntriesAndInfoMetadata();
7180
7181 // Create and register the offloading binary descriptors. This is the main
7182 // entity that captures all the information about offloading in the current
7183 // compilation unit.
7184 return createOffloadingBinaryDescriptorRegistration();
7185}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007186
7187void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7188 const OMPExecutableDirective &D,
7189 SourceLocation Loc,
7190 llvm::Value *OutlinedFn,
7191 ArrayRef<llvm::Value *> CapturedVars) {
7192 if (!CGF.HaveInsertPoint())
7193 return;
7194
7195 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7196 CodeGenFunction::RunCleanupsScope Scope(CGF);
7197
7198 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7199 llvm::Value *Args[] = {
7200 RTLoc,
7201 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7202 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7203 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7204 RealArgs.append(std::begin(Args), std::end(Args));
7205 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7206
7207 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7208 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7209}
7210
7211void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007212 const Expr *NumTeams,
7213 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007214 SourceLocation Loc) {
7215 if (!CGF.HaveInsertPoint())
7216 return;
7217
7218 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7219
Carlo Bertollic6872252016-04-04 15:55:02 +00007220 llvm::Value *NumTeamsVal =
7221 (NumTeams)
7222 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7223 CGF.CGM.Int32Ty, /* isSigned = */ true)
7224 : CGF.Builder.getInt32(0);
7225
7226 llvm::Value *ThreadLimitVal =
7227 (ThreadLimit)
7228 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7229 CGF.CGM.Int32Ty, /* isSigned = */ true)
7230 : CGF.Builder.getInt32(0);
7231
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007232 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007233 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7234 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007235 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7236 PushNumTeamsArgs);
7237}
Samuel Antaodf158d52016-04-27 22:58:19 +00007238
Samuel Antaocc10b852016-07-28 14:23:26 +00007239void CGOpenMPRuntime::emitTargetDataCalls(
7240 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7241 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007242 if (!CGF.HaveInsertPoint())
7243 return;
7244
Samuel Antaocc10b852016-07-28 14:23:26 +00007245 // Action used to replace the default codegen action and turn privatization
7246 // off.
7247 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007248
7249 // Generate the code for the opening of the data environment. Capture all the
7250 // arguments of the runtime call by reference because they are used in the
7251 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007252 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7253 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007254 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007255 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007256 MappableExprsHandler::MapValuesArrayTy Pointers;
7257 MappableExprsHandler::MapValuesArrayTy Sizes;
7258 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7259
7260 // Get map clause information.
7261 MappableExprsHandler MCHandler(D, CGF);
7262 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007263
7264 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007265 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007266
7267 llvm::Value *BasePointersArrayArg = nullptr;
7268 llvm::Value *PointersArrayArg = nullptr;
7269 llvm::Value *SizesArrayArg = nullptr;
7270 llvm::Value *MapTypesArrayArg = nullptr;
7271 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007272 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007273
7274 // Emit device ID if any.
7275 llvm::Value *DeviceID = nullptr;
7276 if (Device)
7277 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7278 CGF.Int32Ty, /*isSigned=*/true);
7279 else
7280 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7281
7282 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007283 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007284
7285 llvm::Value *OffloadingArgs[] = {
7286 DeviceID, PointerNum, BasePointersArrayArg,
7287 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7288 auto &RT = CGF.CGM.getOpenMPRuntime();
7289 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7290 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007291
7292 // If device pointer privatization is required, emit the body of the region
7293 // here. It will have to be duplicated: with and without privatization.
7294 if (!Info.CaptureDeviceAddrMap.empty())
7295 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007296 };
7297
7298 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007299 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007300 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007301
7302 llvm::Value *BasePointersArrayArg = nullptr;
7303 llvm::Value *PointersArrayArg = nullptr;
7304 llvm::Value *SizesArrayArg = nullptr;
7305 llvm::Value *MapTypesArrayArg = nullptr;
7306 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007307 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007308
7309 // Emit device ID if any.
7310 llvm::Value *DeviceID = nullptr;
7311 if (Device)
7312 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7313 CGF.Int32Ty, /*isSigned=*/true);
7314 else
7315 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7316
7317 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007318 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007319
7320 llvm::Value *OffloadingArgs[] = {
7321 DeviceID, PointerNum, BasePointersArrayArg,
7322 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7323 auto &RT = CGF.CGM.getOpenMPRuntime();
7324 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7325 OffloadingArgs);
7326 };
7327
Samuel Antaocc10b852016-07-28 14:23:26 +00007328 // If we need device pointer privatization, we need to emit the body of the
7329 // region with no privatization in the 'else' branch of the conditional.
7330 // Otherwise, we don't have to do anything.
7331 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7332 PrePostActionTy &) {
7333 if (!Info.CaptureDeviceAddrMap.empty()) {
7334 CodeGen.setAction(NoPrivAction);
7335 CodeGen(CGF);
7336 }
7337 };
7338
7339 // We don't have to do anything to close the region if the if clause evaluates
7340 // to false.
7341 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007342
7343 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007344 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007345 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007346 RegionCodeGenTy RCG(BeginThenGen);
7347 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007348 }
7349
Samuel Antaocc10b852016-07-28 14:23:26 +00007350 // If we don't require privatization of device pointers, we emit the body in
7351 // between the runtime calls. This avoids duplicating the body code.
7352 if (Info.CaptureDeviceAddrMap.empty()) {
7353 CodeGen.setAction(NoPrivAction);
7354 CodeGen(CGF);
7355 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007356
7357 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007358 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007359 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007360 RegionCodeGenTy RCG(EndThenGen);
7361 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007362 }
7363}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007364
Samuel Antao8d2d7302016-05-26 18:30:22 +00007365void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007366 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7367 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007368 if (!CGF.HaveInsertPoint())
7369 return;
7370
Samuel Antao8dd66282016-04-27 23:14:30 +00007371 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007372 isa<OMPTargetExitDataDirective>(D) ||
7373 isa<OMPTargetUpdateDirective>(D)) &&
7374 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007375
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007376 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007377 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007378 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007379 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007380 MappableExprsHandler::MapValuesArrayTy Pointers;
7381 MappableExprsHandler::MapValuesArrayTy Sizes;
7382 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7383
7384 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007385 MappableExprsHandler MEHandler(D, CGF);
7386 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007387
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007388 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007389 TargetDataInfo Info;
7390 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7391 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7392 Info.PointersArray, Info.SizesArray,
7393 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007394
7395 // Emit device ID if any.
7396 llvm::Value *DeviceID = nullptr;
7397 if (Device)
7398 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7399 CGF.Int32Ty, /*isSigned=*/true);
7400 else
7401 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7402
7403 // Emit the number of elements in the offloading arrays.
7404 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7405
7406 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007407 DeviceID, PointerNum, Info.BasePointersArray,
7408 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007409
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007410 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007411 // Select the right runtime function call for each expected standalone
7412 // directive.
7413 OpenMPRTLFunction RTLFn;
7414 switch (D.getDirectiveKind()) {
7415 default:
7416 llvm_unreachable("Unexpected standalone target data directive.");
7417 break;
7418 case OMPD_target_enter_data:
7419 RTLFn = OMPRTL__tgt_target_data_begin;
7420 break;
7421 case OMPD_target_exit_data:
7422 RTLFn = OMPRTL__tgt_target_data_end;
7423 break;
7424 case OMPD_target_update:
7425 RTLFn = OMPRTL__tgt_target_data_update;
7426 break;
7427 }
7428 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007429 };
7430
7431 // In the event we get an if clause, we don't have to take any action on the
7432 // else side.
7433 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7434
7435 if (IfCond) {
7436 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7437 } else {
7438 RegionCodeGenTy ThenGenRCG(ThenGen);
7439 ThenGenRCG(CGF);
7440 }
7441}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007442
7443namespace {
7444 /// Kind of parameter in a function with 'declare simd' directive.
7445 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7446 /// Attribute set of the parameter.
7447 struct ParamAttrTy {
7448 ParamKindTy Kind = Vector;
7449 llvm::APSInt StrideOrArg;
7450 llvm::APSInt Alignment;
7451 };
7452} // namespace
7453
7454static unsigned evaluateCDTSize(const FunctionDecl *FD,
7455 ArrayRef<ParamAttrTy> ParamAttrs) {
7456 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7457 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7458 // of that clause. The VLEN value must be power of 2.
7459 // In other case the notion of the function`s "characteristic data type" (CDT)
7460 // is used to compute the vector length.
7461 // CDT is defined in the following order:
7462 // a) For non-void function, the CDT is the return type.
7463 // b) If the function has any non-uniform, non-linear parameters, then the
7464 // CDT is the type of the first such parameter.
7465 // c) If the CDT determined by a) or b) above is struct, union, or class
7466 // type which is pass-by-value (except for the type that maps to the
7467 // built-in complex data type), the characteristic data type is int.
7468 // d) If none of the above three cases is applicable, the CDT is int.
7469 // The VLEN is then determined based on the CDT and the size of vector
7470 // register of that ISA for which current vector version is generated. The
7471 // VLEN is computed using the formula below:
7472 // VLEN = sizeof(vector_register) / sizeof(CDT),
7473 // where vector register size specified in section 3.2.1 Registers and the
7474 // Stack Frame of original AMD64 ABI document.
7475 QualType RetType = FD->getReturnType();
7476 if (RetType.isNull())
7477 return 0;
7478 ASTContext &C = FD->getASTContext();
7479 QualType CDT;
7480 if (!RetType.isNull() && !RetType->isVoidType())
7481 CDT = RetType;
7482 else {
7483 unsigned Offset = 0;
7484 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7485 if (ParamAttrs[Offset].Kind == Vector)
7486 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7487 ++Offset;
7488 }
7489 if (CDT.isNull()) {
7490 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7491 if (ParamAttrs[I + Offset].Kind == Vector) {
7492 CDT = FD->getParamDecl(I)->getType();
7493 break;
7494 }
7495 }
7496 }
7497 }
7498 if (CDT.isNull())
7499 CDT = C.IntTy;
7500 CDT = CDT->getCanonicalTypeUnqualified();
7501 if (CDT->isRecordType() || CDT->isUnionType())
7502 CDT = C.IntTy;
7503 return C.getTypeSize(CDT);
7504}
7505
7506static void
7507emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007508 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007509 ArrayRef<ParamAttrTy> ParamAttrs,
7510 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7511 struct ISADataTy {
7512 char ISA;
7513 unsigned VecRegSize;
7514 };
7515 ISADataTy ISAData[] = {
7516 {
7517 'b', 128
7518 }, // SSE
7519 {
7520 'c', 256
7521 }, // AVX
7522 {
7523 'd', 256
7524 }, // AVX2
7525 {
7526 'e', 512
7527 }, // AVX512
7528 };
7529 llvm::SmallVector<char, 2> Masked;
7530 switch (State) {
7531 case OMPDeclareSimdDeclAttr::BS_Undefined:
7532 Masked.push_back('N');
7533 Masked.push_back('M');
7534 break;
7535 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7536 Masked.push_back('N');
7537 break;
7538 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7539 Masked.push_back('M');
7540 break;
7541 }
7542 for (auto Mask : Masked) {
7543 for (auto &Data : ISAData) {
7544 SmallString<256> Buffer;
7545 llvm::raw_svector_ostream Out(Buffer);
7546 Out << "_ZGV" << Data.ISA << Mask;
7547 if (!VLENVal) {
7548 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7549 evaluateCDTSize(FD, ParamAttrs));
7550 } else
7551 Out << VLENVal;
7552 for (auto &ParamAttr : ParamAttrs) {
7553 switch (ParamAttr.Kind){
7554 case LinearWithVarStride:
7555 Out << 's' << ParamAttr.StrideOrArg;
7556 break;
7557 case Linear:
7558 Out << 'l';
7559 if (!!ParamAttr.StrideOrArg)
7560 Out << ParamAttr.StrideOrArg;
7561 break;
7562 case Uniform:
7563 Out << 'u';
7564 break;
7565 case Vector:
7566 Out << 'v';
7567 break;
7568 }
7569 if (!!ParamAttr.Alignment)
7570 Out << 'a' << ParamAttr.Alignment;
7571 }
7572 Out << '_' << Fn->getName();
7573 Fn->addFnAttr(Out.str());
7574 }
7575 }
7576}
7577
7578void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7579 llvm::Function *Fn) {
7580 ASTContext &C = CGM.getContext();
7581 FD = FD->getCanonicalDecl();
7582 // Map params to their positions in function decl.
7583 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7584 if (isa<CXXMethodDecl>(FD))
7585 ParamPositions.insert({FD, 0});
7586 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007587 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007588 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7589 ++ParamPos;
7590 }
7591 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7592 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7593 // Mark uniform parameters.
7594 for (auto *E : Attr->uniforms()) {
7595 E = E->IgnoreParenImpCasts();
7596 unsigned Pos;
7597 if (isa<CXXThisExpr>(E))
7598 Pos = ParamPositions[FD];
7599 else {
7600 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7601 ->getCanonicalDecl();
7602 Pos = ParamPositions[PVD];
7603 }
7604 ParamAttrs[Pos].Kind = Uniform;
7605 }
7606 // Get alignment info.
7607 auto NI = Attr->alignments_begin();
7608 for (auto *E : Attr->aligneds()) {
7609 E = E->IgnoreParenImpCasts();
7610 unsigned Pos;
7611 QualType ParmTy;
7612 if (isa<CXXThisExpr>(E)) {
7613 Pos = ParamPositions[FD];
7614 ParmTy = E->getType();
7615 } else {
7616 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7617 ->getCanonicalDecl();
7618 Pos = ParamPositions[PVD];
7619 ParmTy = PVD->getType();
7620 }
7621 ParamAttrs[Pos].Alignment =
7622 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7623 : llvm::APSInt::getUnsigned(
7624 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7625 .getQuantity());
7626 ++NI;
7627 }
7628 // Mark linear parameters.
7629 auto SI = Attr->steps_begin();
7630 auto MI = Attr->modifiers_begin();
7631 for (auto *E : Attr->linears()) {
7632 E = E->IgnoreParenImpCasts();
7633 unsigned Pos;
7634 if (isa<CXXThisExpr>(E))
7635 Pos = ParamPositions[FD];
7636 else {
7637 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7638 ->getCanonicalDecl();
7639 Pos = ParamPositions[PVD];
7640 }
7641 auto &ParamAttr = ParamAttrs[Pos];
7642 ParamAttr.Kind = Linear;
7643 if (*SI) {
7644 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7645 Expr::SE_AllowSideEffects)) {
7646 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7647 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7648 ParamAttr.Kind = LinearWithVarStride;
7649 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7650 ParamPositions[StridePVD->getCanonicalDecl()]);
7651 }
7652 }
7653 }
7654 }
7655 ++SI;
7656 ++MI;
7657 }
7658 llvm::APSInt VLENVal;
7659 if (const Expr *VLEN = Attr->getSimdlen())
7660 VLENVal = VLEN->EvaluateKnownConstInt(C);
7661 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7662 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7663 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7664 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7665 }
7666}
Alexey Bataev8b427062016-05-25 12:36:08 +00007667
7668namespace {
7669/// Cleanup action for doacross support.
7670class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7671public:
7672 static const int DoacrossFinArgs = 2;
7673
7674private:
7675 llvm::Value *RTLFn;
7676 llvm::Value *Args[DoacrossFinArgs];
7677
7678public:
7679 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7680 : RTLFn(RTLFn) {
7681 assert(CallArgs.size() == DoacrossFinArgs);
7682 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7683 }
7684 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7685 if (!CGF.HaveInsertPoint())
7686 return;
7687 CGF.EmitRuntimeCall(RTLFn, Args);
7688 }
7689};
7690} // namespace
7691
7692void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7693 const OMPLoopDirective &D) {
7694 if (!CGF.HaveInsertPoint())
7695 return;
7696
7697 ASTContext &C = CGM.getContext();
7698 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7699 RecordDecl *RD;
7700 if (KmpDimTy.isNull()) {
7701 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7702 // kmp_int64 lo; // lower
7703 // kmp_int64 up; // upper
7704 // kmp_int64 st; // stride
7705 // };
7706 RD = C.buildImplicitRecord("kmp_dim");
7707 RD->startDefinition();
7708 addFieldToRecordDecl(C, RD, Int64Ty);
7709 addFieldToRecordDecl(C, RD, Int64Ty);
7710 addFieldToRecordDecl(C, RD, Int64Ty);
7711 RD->completeDefinition();
7712 KmpDimTy = C.getRecordType(RD);
7713 } else
7714 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7715
7716 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7717 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7718 enum { LowerFD = 0, UpperFD, StrideFD };
7719 // Fill dims with data.
7720 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7721 // dims.upper = num_iterations;
7722 LValue UpperLVal =
7723 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7724 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7725 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7726 Int64Ty, D.getNumIterations()->getExprLoc());
7727 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7728 // dims.stride = 1;
7729 LValue StrideLVal =
7730 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7731 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7732 StrideLVal);
7733
7734 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7735 // kmp_int32 num_dims, struct kmp_dim * dims);
7736 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7737 getThreadID(CGF, D.getLocStart()),
7738 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7739 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7740 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7741
7742 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7743 CGF.EmitRuntimeCall(RTLFn, Args);
7744 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7745 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7746 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7747 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7748 llvm::makeArrayRef(FiniArgs));
7749}
7750
7751void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7752 const OMPDependClause *C) {
7753 QualType Int64Ty =
7754 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7755 const Expr *CounterVal = C->getCounterValue();
7756 assert(CounterVal);
7757 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7758 CounterVal->getType(), Int64Ty,
7759 CounterVal->getExprLoc());
7760 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7761 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7762 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7763 getThreadID(CGF, C->getLocStart()),
7764 CntAddr.getPointer()};
7765 llvm::Value *RTLFn;
7766 if (C->getDependencyKind() == OMPC_DEPEND_source)
7767 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7768 else {
7769 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7770 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7771 }
7772 CGF.EmitRuntimeCall(RTLFn, Args);
7773}
7774
Alexey Bataev3c595a62017-08-14 15:01:03 +00007775void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7776 ArrayRef<llvm::Value *> Args,
7777 SourceLocation Loc) const {
7778 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7779
7780 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007781 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007782 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007783 return;
7784 }
7785 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007786 CGF.EmitRuntimeCall(Callee, Args);
7787}
7788
7789void CGOpenMPRuntime::emitOutlinedFunctionCall(
7790 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7791 ArrayRef<llvm::Value *> Args) const {
7792 assert(Loc.isValid() && "Outlined function call location must be valid.");
7793 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007794}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007795
7796Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7797 const VarDecl *NativeParam,
7798 const VarDecl *TargetParam) const {
7799 return CGF.GetAddrOfLocalVar(NativeParam);
7800}