blob: c462b042ff5938ed26aa8b000e638b99690eeccb [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();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001203 if (!IsCombiner && Out->hasInit() &&
1204 !CGF.isTrivialInitializer(Out->getInit())) {
1205 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1206 Out->getType().getQualifiers(),
1207 /*IsInitializer=*/true);
1208 }
1209 if (CombinerInitializer)
1210 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001211 Scope.ForceCleanup();
1212 CGF.FinishFunction();
1213 return Fn;
1214}
1215
1216void CGOpenMPRuntime::emitUserDefinedReduction(
1217 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1218 if (UDRMap.count(D) > 0)
1219 return;
1220 auto &C = CGM.getContext();
1221 if (!In || !Out) {
1222 In = &C.Idents.get("omp_in");
1223 Out = &C.Idents.get("omp_out");
1224 }
1225 llvm::Function *Combiner = emitCombinerOrInitializer(
1226 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1227 cast<VarDecl>(D->lookup(Out).front()),
1228 /*IsCombiner=*/true);
1229 llvm::Function *Initializer = nullptr;
1230 if (auto *Init = D->getInitializer()) {
1231 if (!Priv || !Orig) {
1232 Priv = &C.Idents.get("omp_priv");
1233 Orig = &C.Idents.get("omp_orig");
1234 }
1235 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001236 CGM, D->getType(),
1237 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1238 : nullptr,
1239 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001240 cast<VarDecl>(D->lookup(Priv).front()),
1241 /*IsCombiner=*/false);
1242 }
1243 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1244 if (CGF) {
1245 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1246 Decls.second.push_back(D);
1247 }
1248}
1249
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001250std::pair<llvm::Function *, llvm::Function *>
1251CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1252 auto I = UDRMap.find(D);
1253 if (I != UDRMap.end())
1254 return I->second;
1255 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1256 return UDRMap.lookup(D);
1257}
1258
John McCall7f416cc2015-09-08 08:05:57 +00001259// Layout information for ident_t.
1260static CharUnits getIdentAlign(CodeGenModule &CGM) {
1261 return CGM.getPointerAlign();
1262}
1263static CharUnits getIdentSize(CodeGenModule &CGM) {
1264 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1265 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1266}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001267static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001268 // All the fields except the last are i32, so this works beautifully.
1269 return unsigned(Field) * CharUnits::fromQuantity(4);
1270}
1271static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001272 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001273 const llvm::Twine &Name = "") {
1274 auto Offset = getOffsetOfIdentField(Field);
1275 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1276}
1277
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001278static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1279 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1280 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1281 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001282 assert(ThreadIDVar->getType()->isPointerType() &&
1283 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001284 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001285 bool HasCancel = false;
1286 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1287 HasCancel = OPD->hasCancel();
1288 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1289 HasCancel = OPSD->hasCancel();
1290 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1291 HasCancel = OPFD->hasCancel();
1292 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001293 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001294 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001295 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001296}
1297
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001298llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1299 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1300 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1301 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1302 return emitParallelOrTeamsOutlinedFunction(
1303 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1304}
1305
1306llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1307 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1308 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1309 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1310 return emitParallelOrTeamsOutlinedFunction(
1311 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1312}
1313
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001314llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1315 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001316 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1317 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1318 bool Tied, unsigned &NumberOfParts) {
1319 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1320 PrePostActionTy &) {
1321 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1322 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1323 llvm::Value *TaskArgs[] = {
1324 UpLoc, ThreadID,
1325 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1326 TaskTVar->getType()->castAs<PointerType>())
1327 .getPointer()};
1328 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1329 };
1330 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1331 UntiedCodeGen);
1332 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001333 assert(!ThreadIDVar->getType()->isPointerType() &&
1334 "thread id variable must be of type kmp_int32 for tasks");
1335 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001336 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001337 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001338 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1339 InnermostKind,
1340 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001341 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001342 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1343 if (!Tied)
1344 NumberOfParts = Action.getNumberOfParts();
1345 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001346}
1347
Alexey Bataev50b3c952016-02-19 10:38:26 +00001348Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001349 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001350 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001351 if (!Entry) {
1352 if (!DefaultOpenMPPSource) {
1353 // Initialize default location for psource field of ident_t structure of
1354 // all ident_t objects. Format is ";file;function;line;column;;".
1355 // Taken from
1356 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1357 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001358 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001359 DefaultOpenMPPSource =
1360 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1361 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001362
John McCall23c9dc62016-11-28 22:18:27 +00001363 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001364 auto fields = builder.beginStruct(IdentTy);
1365 fields.addInt(CGM.Int32Ty, 0);
1366 fields.addInt(CGM.Int32Ty, Flags);
1367 fields.addInt(CGM.Int32Ty, 0);
1368 fields.addInt(CGM.Int32Ty, 0);
1369 fields.add(DefaultOpenMPPSource);
1370 auto DefaultOpenMPLocation =
1371 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1372 llvm::GlobalValue::PrivateLinkage);
1373 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1374
John McCall7f416cc2015-09-08 08:05:57 +00001375 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001376 }
John McCall7f416cc2015-09-08 08:05:57 +00001377 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001378}
1379
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001380llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1381 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001382 unsigned Flags) {
1383 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001384 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001385 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001386 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001387 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001388
1389 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1390
John McCall7f416cc2015-09-08 08:05:57 +00001391 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001392 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1393 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001394 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1395
Alexander Musmanc6388682014-12-15 07:07:06 +00001396 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1397 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001398 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001399 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001400 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1401 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001402 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001403 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001404 LocValue = AI;
1405
1406 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1407 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001408 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001409 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001410 }
1411
1412 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001413 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001414
Alexey Bataevf002aca2014-05-30 05:48:40 +00001415 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1416 if (OMPDebugLoc == nullptr) {
1417 SmallString<128> Buffer2;
1418 llvm::raw_svector_ostream OS2(Buffer2);
1419 // Build debug location
1420 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1421 OS2 << ";" << PLoc.getFilename() << ";";
1422 if (const FunctionDecl *FD =
1423 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1424 OS2 << FD->getQualifiedNameAsString();
1425 }
1426 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1427 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1428 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001429 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001430 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001431 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1432
John McCall7f416cc2015-09-08 08:05:57 +00001433 // Our callers always pass this to a runtime function, so for
1434 // convenience, go ahead and return a naked pointer.
1435 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001436}
1437
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001438llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1439 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001440 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1441
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001442 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001443 // Check whether we've already cached a load of the thread id in this
1444 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001445 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001446 if (I != OpenMPLocThreadIDMap.end()) {
1447 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001448 if (ThreadID != nullptr)
1449 return ThreadID;
1450 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001451 // If exceptions are enabled, do not use parameter to avoid possible crash.
1452 if (!CGF.getInvokeDest()) {
1453 if (auto *OMPRegionInfo =
1454 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1455 if (OMPRegionInfo->getThreadIDVariable()) {
1456 // Check if this an outlined function with thread id passed as argument.
1457 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1458 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1459 // If value loaded in entry block, cache it and use it everywhere in
1460 // function.
1461 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1462 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1463 Elem.second.ThreadID = ThreadID;
1464 }
1465 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001466 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001467 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001468 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001469
1470 // This is not an outlined function region - need to call __kmpc_int32
1471 // kmpc_global_thread_num(ident_t *loc).
1472 // Generate thread id value and cache this value for use across the
1473 // function.
1474 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1475 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1476 ThreadID =
1477 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1478 emitUpdateLocation(CGF, Loc));
1479 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1480 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001481 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001482}
1483
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001484void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001485 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001486 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1487 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001488 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1489 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1490 UDRMap.erase(D);
1491 }
1492 FunctionUDRMap.erase(CGF.CurFn);
1493 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001494}
1495
1496llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001497 if (!IdentTy) {
1498 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001499 return llvm::PointerType::getUnqual(IdentTy);
1500}
1501
1502llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001503 if (!Kmpc_MicroTy) {
1504 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1505 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1506 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1507 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1508 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001509 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1510}
1511
1512llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001513CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001514 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001515 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001516 case OMPRTL__kmpc_fork_call: {
1517 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1518 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001519 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1520 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001521 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001522 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001523 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1524 break;
1525 }
1526 case OMPRTL__kmpc_global_thread_num: {
1527 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001528 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001529 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001530 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001531 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1532 break;
1533 }
Alexey Bataev97720002014-11-11 04:05:39 +00001534 case OMPRTL__kmpc_threadprivate_cached: {
1535 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1536 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1537 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1538 CGM.VoidPtrTy, CGM.SizeTy,
1539 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1540 llvm::FunctionType *FnTy =
1541 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1542 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1543 break;
1544 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001545 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001546 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1547 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001548 llvm::Type *TypeParams[] = {
1549 getIdentTyPointerTy(), CGM.Int32Ty,
1550 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1551 llvm::FunctionType *FnTy =
1552 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1553 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1554 break;
1555 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001556 case OMPRTL__kmpc_critical_with_hint: {
1557 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1558 // kmp_critical_name *crit, uintptr_t hint);
1559 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1560 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1561 CGM.IntPtrTy};
1562 llvm::FunctionType *FnTy =
1563 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1564 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1565 break;
1566 }
Alexey Bataev97720002014-11-11 04:05:39 +00001567 case OMPRTL__kmpc_threadprivate_register: {
1568 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1569 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1570 // typedef void *(*kmpc_ctor)(void *);
1571 auto KmpcCtorTy =
1572 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1573 /*isVarArg*/ false)->getPointerTo();
1574 // typedef void *(*kmpc_cctor)(void *, void *);
1575 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1576 auto KmpcCopyCtorTy =
1577 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1578 /*isVarArg*/ false)->getPointerTo();
1579 // typedef void (*kmpc_dtor)(void *);
1580 auto KmpcDtorTy =
1581 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1582 ->getPointerTo();
1583 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1584 KmpcCopyCtorTy, KmpcDtorTy};
1585 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1586 /*isVarArg*/ false);
1587 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1588 break;
1589 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001590 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001591 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1592 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001593 llvm::Type *TypeParams[] = {
1594 getIdentTyPointerTy(), CGM.Int32Ty,
1595 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1596 llvm::FunctionType *FnTy =
1597 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1599 break;
1600 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001601 case OMPRTL__kmpc_cancel_barrier: {
1602 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1603 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001604 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1605 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001606 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1607 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001608 break;
1609 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001610 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001611 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001612 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1613 llvm::FunctionType *FnTy =
1614 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1615 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1616 break;
1617 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001618 case OMPRTL__kmpc_for_static_fini: {
1619 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1620 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1621 llvm::FunctionType *FnTy =
1622 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1623 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1624 break;
1625 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001626 case OMPRTL__kmpc_push_num_threads: {
1627 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1628 // kmp_int32 num_threads)
1629 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1630 CGM.Int32Ty};
1631 llvm::FunctionType *FnTy =
1632 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1633 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1634 break;
1635 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001636 case OMPRTL__kmpc_serialized_parallel: {
1637 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1638 // global_tid);
1639 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1640 llvm::FunctionType *FnTy =
1641 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1642 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1643 break;
1644 }
1645 case OMPRTL__kmpc_end_serialized_parallel: {
1646 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1647 // global_tid);
1648 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1649 llvm::FunctionType *FnTy =
1650 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1651 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1652 break;
1653 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001654 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001655 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001656 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1657 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001658 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001659 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1660 break;
1661 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001662 case OMPRTL__kmpc_master: {
1663 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1664 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1665 llvm::FunctionType *FnTy =
1666 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1667 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1668 break;
1669 }
1670 case OMPRTL__kmpc_end_master: {
1671 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1673 llvm::FunctionType *FnTy =
1674 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1675 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1676 break;
1677 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001678 case OMPRTL__kmpc_omp_taskyield: {
1679 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1680 // int end_part);
1681 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1682 llvm::FunctionType *FnTy =
1683 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1684 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1685 break;
1686 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001687 case OMPRTL__kmpc_single: {
1688 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1689 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1690 llvm::FunctionType *FnTy =
1691 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1692 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1693 break;
1694 }
1695 case OMPRTL__kmpc_end_single: {
1696 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1697 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1698 llvm::FunctionType *FnTy =
1699 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1700 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1701 break;
1702 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001703 case OMPRTL__kmpc_omp_task_alloc: {
1704 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1705 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1706 // kmp_routine_entry_t *task_entry);
1707 assert(KmpRoutineEntryPtrTy != nullptr &&
1708 "Type kmp_routine_entry_t must be created.");
1709 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1710 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1711 // Return void * and then cast to particular kmp_task_t type.
1712 llvm::FunctionType *FnTy =
1713 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1714 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1715 break;
1716 }
1717 case OMPRTL__kmpc_omp_task: {
1718 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1719 // *new_task);
1720 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1721 CGM.VoidPtrTy};
1722 llvm::FunctionType *FnTy =
1723 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1724 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1725 break;
1726 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001727 case OMPRTL__kmpc_copyprivate: {
1728 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001729 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001730 // kmp_int32 didit);
1731 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1732 auto *CpyFnTy =
1733 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001734 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001735 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1736 CGM.Int32Ty};
1737 llvm::FunctionType *FnTy =
1738 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1739 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1740 break;
1741 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001742 case OMPRTL__kmpc_reduce: {
1743 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1744 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1745 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1746 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1747 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1748 /*isVarArg=*/false);
1749 llvm::Type *TypeParams[] = {
1750 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1751 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1752 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1753 llvm::FunctionType *FnTy =
1754 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1755 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1756 break;
1757 }
1758 case OMPRTL__kmpc_reduce_nowait: {
1759 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1760 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1761 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1762 // *lck);
1763 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1764 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1765 /*isVarArg=*/false);
1766 llvm::Type *TypeParams[] = {
1767 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1768 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1769 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1770 llvm::FunctionType *FnTy =
1771 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1772 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1773 break;
1774 }
1775 case OMPRTL__kmpc_end_reduce: {
1776 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1777 // kmp_critical_name *lck);
1778 llvm::Type *TypeParams[] = {
1779 getIdentTyPointerTy(), CGM.Int32Ty,
1780 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1781 llvm::FunctionType *FnTy =
1782 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1783 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1784 break;
1785 }
1786 case OMPRTL__kmpc_end_reduce_nowait: {
1787 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1788 // kmp_critical_name *lck);
1789 llvm::Type *TypeParams[] = {
1790 getIdentTyPointerTy(), CGM.Int32Ty,
1791 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1792 llvm::FunctionType *FnTy =
1793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1794 RTLFn =
1795 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1796 break;
1797 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001798 case OMPRTL__kmpc_omp_task_begin_if0: {
1799 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1800 // *new_task);
1801 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1802 CGM.VoidPtrTy};
1803 llvm::FunctionType *FnTy =
1804 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1805 RTLFn =
1806 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1807 break;
1808 }
1809 case OMPRTL__kmpc_omp_task_complete_if0: {
1810 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1811 // *new_task);
1812 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1813 CGM.VoidPtrTy};
1814 llvm::FunctionType *FnTy =
1815 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1816 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1817 /*Name=*/"__kmpc_omp_task_complete_if0");
1818 break;
1819 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001820 case OMPRTL__kmpc_ordered: {
1821 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1822 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1823 llvm::FunctionType *FnTy =
1824 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1825 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1826 break;
1827 }
1828 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001829 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001830 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1831 llvm::FunctionType *FnTy =
1832 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1833 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1834 break;
1835 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001836 case OMPRTL__kmpc_omp_taskwait: {
1837 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1838 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1839 llvm::FunctionType *FnTy =
1840 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1841 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1842 break;
1843 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001844 case OMPRTL__kmpc_taskgroup: {
1845 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1846 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1847 llvm::FunctionType *FnTy =
1848 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1849 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1850 break;
1851 }
1852 case OMPRTL__kmpc_end_taskgroup: {
1853 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1854 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1855 llvm::FunctionType *FnTy =
1856 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1857 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1858 break;
1859 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001860 case OMPRTL__kmpc_push_proc_bind: {
1861 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1862 // int proc_bind)
1863 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1864 llvm::FunctionType *FnTy =
1865 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1866 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1867 break;
1868 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001869 case OMPRTL__kmpc_omp_task_with_deps: {
1870 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1871 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1872 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1873 llvm::Type *TypeParams[] = {
1874 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1875 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1876 llvm::FunctionType *FnTy =
1877 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1878 RTLFn =
1879 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1880 break;
1881 }
1882 case OMPRTL__kmpc_omp_wait_deps: {
1883 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1884 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1885 // kmp_depend_info_t *noalias_dep_list);
1886 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1887 CGM.Int32Ty, CGM.VoidPtrTy,
1888 CGM.Int32Ty, CGM.VoidPtrTy};
1889 llvm::FunctionType *FnTy =
1890 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1891 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1892 break;
1893 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001894 case OMPRTL__kmpc_cancellationpoint: {
1895 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1896 // global_tid, kmp_int32 cncl_kind)
1897 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1898 llvm::FunctionType *FnTy =
1899 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1900 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1901 break;
1902 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001903 case OMPRTL__kmpc_cancel: {
1904 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1905 // kmp_int32 cncl_kind)
1906 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1907 llvm::FunctionType *FnTy =
1908 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1909 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1910 break;
1911 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001912 case OMPRTL__kmpc_push_num_teams: {
1913 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1914 // kmp_int32 num_teams, kmp_int32 num_threads)
1915 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1916 CGM.Int32Ty};
1917 llvm::FunctionType *FnTy =
1918 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1919 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1920 break;
1921 }
1922 case OMPRTL__kmpc_fork_teams: {
1923 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1924 // microtask, ...);
1925 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1926 getKmpc_MicroPointerTy()};
1927 llvm::FunctionType *FnTy =
1928 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1929 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1930 break;
1931 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001932 case OMPRTL__kmpc_taskloop: {
1933 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1934 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1935 // sched, kmp_uint64 grainsize, void *task_dup);
1936 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1937 CGM.IntTy,
1938 CGM.VoidPtrTy,
1939 CGM.IntTy,
1940 CGM.Int64Ty->getPointerTo(),
1941 CGM.Int64Ty->getPointerTo(),
1942 CGM.Int64Ty,
1943 CGM.IntTy,
1944 CGM.IntTy,
1945 CGM.Int64Ty,
1946 CGM.VoidPtrTy};
1947 llvm::FunctionType *FnTy =
1948 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1949 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1950 break;
1951 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001952 case OMPRTL__kmpc_doacross_init: {
1953 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1954 // num_dims, struct kmp_dim *dims);
1955 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1956 CGM.Int32Ty,
1957 CGM.Int32Ty,
1958 CGM.VoidPtrTy};
1959 llvm::FunctionType *FnTy =
1960 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1961 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1962 break;
1963 }
1964 case OMPRTL__kmpc_doacross_fini: {
1965 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1966 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1967 llvm::FunctionType *FnTy =
1968 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1969 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1970 break;
1971 }
1972 case OMPRTL__kmpc_doacross_post: {
1973 // Build void __kmpc_doacross_post(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_post");
1980 break;
1981 }
1982 case OMPRTL__kmpc_doacross_wait: {
1983 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1984 // *vec);
1985 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1986 CGM.Int64Ty->getPointerTo()};
1987 llvm::FunctionType *FnTy =
1988 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1989 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1990 break;
1991 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001992 case OMPRTL__kmpc_task_reduction_init: {
1993 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1994 // *data);
1995 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
1996 llvm::FunctionType *FnTy =
1997 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1998 RTLFn =
1999 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2000 break;
2001 }
2002 case OMPRTL__kmpc_task_reduction_get_th_data: {
2003 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2004 // *d);
2005 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2006 llvm::FunctionType *FnTy =
2007 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2008 RTLFn = CGM.CreateRuntimeFunction(
2009 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2010 break;
2011 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002012 case OMPRTL__tgt_target: {
2013 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
2014 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
2015 // *arg_types);
2016 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2017 CGM.VoidPtrTy,
2018 CGM.Int32Ty,
2019 CGM.VoidPtrPtrTy,
2020 CGM.VoidPtrPtrTy,
2021 CGM.SizeTy->getPointerTo(),
2022 CGM.Int32Ty->getPointerTo()};
2023 llvm::FunctionType *FnTy =
2024 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2025 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2026 break;
2027 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002028 case OMPRTL__tgt_target_teams: {
2029 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2030 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2031 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2032 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2033 CGM.VoidPtrTy,
2034 CGM.Int32Ty,
2035 CGM.VoidPtrPtrTy,
2036 CGM.VoidPtrPtrTy,
2037 CGM.SizeTy->getPointerTo(),
2038 CGM.Int32Ty->getPointerTo(),
2039 CGM.Int32Ty,
2040 CGM.Int32Ty};
2041 llvm::FunctionType *FnTy =
2042 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2043 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2044 break;
2045 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002046 case OMPRTL__tgt_register_lib: {
2047 // Build void __tgt_register_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_register_lib");
2054 break;
2055 }
2056 case OMPRTL__tgt_unregister_lib: {
2057 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2058 QualType ParamTy =
2059 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2060 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2061 llvm::FunctionType *FnTy =
2062 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2063 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2064 break;
2065 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002066 case OMPRTL__tgt_target_data_begin: {
2067 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2068 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2069 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2070 CGM.Int32Ty,
2071 CGM.VoidPtrPtrTy,
2072 CGM.VoidPtrPtrTy,
2073 CGM.SizeTy->getPointerTo(),
2074 CGM.Int32Ty->getPointerTo()};
2075 llvm::FunctionType *FnTy =
2076 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2077 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2078 break;
2079 }
2080 case OMPRTL__tgt_target_data_end: {
2081 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2082 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2083 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2084 CGM.Int32Ty,
2085 CGM.VoidPtrPtrTy,
2086 CGM.VoidPtrPtrTy,
2087 CGM.SizeTy->getPointerTo(),
2088 CGM.Int32Ty->getPointerTo()};
2089 llvm::FunctionType *FnTy =
2090 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2091 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2092 break;
2093 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002094 case OMPRTL__tgt_target_data_update: {
2095 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2096 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2097 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2098 CGM.Int32Ty,
2099 CGM.VoidPtrPtrTy,
2100 CGM.VoidPtrPtrTy,
2101 CGM.SizeTy->getPointerTo(),
2102 CGM.Int32Ty->getPointerTo()};
2103 llvm::FunctionType *FnTy =
2104 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2105 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2106 break;
2107 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002108 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002109 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002110 return RTLFn;
2111}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002112
Alexander Musman21212e42015-03-13 10:38:23 +00002113llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2114 bool IVSigned) {
2115 assert((IVSize == 32 || IVSize == 64) &&
2116 "IV size is not compatible with the omp runtime");
2117 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2118 : "__kmpc_for_static_init_4u")
2119 : (IVSigned ? "__kmpc_for_static_init_8"
2120 : "__kmpc_for_static_init_8u");
2121 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2122 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2123 llvm::Type *TypeParams[] = {
2124 getIdentTyPointerTy(), // loc
2125 CGM.Int32Ty, // tid
2126 CGM.Int32Ty, // schedtype
2127 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2128 PtrTy, // p_lower
2129 PtrTy, // p_upper
2130 PtrTy, // p_stride
2131 ITy, // incr
2132 ITy // chunk
2133 };
2134 llvm::FunctionType *FnTy =
2135 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2136 return CGM.CreateRuntimeFunction(FnTy, Name);
2137}
2138
Alexander Musman92bdaab2015-03-12 13:37:50 +00002139llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2140 bool IVSigned) {
2141 assert((IVSize == 32 || IVSize == 64) &&
2142 "IV size is not compatible with the omp runtime");
2143 auto Name =
2144 IVSize == 32
2145 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2146 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2147 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2148 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2149 CGM.Int32Ty, // tid
2150 CGM.Int32Ty, // schedtype
2151 ITy, // lower
2152 ITy, // upper
2153 ITy, // stride
2154 ITy // chunk
2155 };
2156 llvm::FunctionType *FnTy =
2157 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2158 return CGM.CreateRuntimeFunction(FnTy, Name);
2159}
2160
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002161llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2162 bool IVSigned) {
2163 assert((IVSize == 32 || IVSize == 64) &&
2164 "IV size is not compatible with the omp runtime");
2165 auto Name =
2166 IVSize == 32
2167 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2168 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2169 llvm::Type *TypeParams[] = {
2170 getIdentTyPointerTy(), // loc
2171 CGM.Int32Ty, // tid
2172 };
2173 llvm::FunctionType *FnTy =
2174 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2175 return CGM.CreateRuntimeFunction(FnTy, Name);
2176}
2177
Alexander Musman92bdaab2015-03-12 13:37:50 +00002178llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2179 bool IVSigned) {
2180 assert((IVSize == 32 || IVSize == 64) &&
2181 "IV size is not compatible with the omp runtime");
2182 auto Name =
2183 IVSize == 32
2184 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2185 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2186 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2187 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2188 llvm::Type *TypeParams[] = {
2189 getIdentTyPointerTy(), // loc
2190 CGM.Int32Ty, // tid
2191 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2192 PtrTy, // p_lower
2193 PtrTy, // p_upper
2194 PtrTy // p_stride
2195 };
2196 llvm::FunctionType *FnTy =
2197 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2198 return CGM.CreateRuntimeFunction(FnTy, Name);
2199}
2200
Alexey Bataev97720002014-11-11 04:05:39 +00002201llvm::Constant *
2202CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002203 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2204 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002205 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002206 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002207 Twine(CGM.getMangledName(VD)) + ".cache.");
2208}
2209
John McCall7f416cc2015-09-08 08:05:57 +00002210Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2211 const VarDecl *VD,
2212 Address VDAddr,
2213 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002214 if (CGM.getLangOpts().OpenMPUseTLS &&
2215 CGM.getContext().getTargetInfo().isTLSSupported())
2216 return VDAddr;
2217
John McCall7f416cc2015-09-08 08:05:57 +00002218 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002219 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002220 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2221 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002222 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2223 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002224 return Address(CGF.EmitRuntimeCall(
2225 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2226 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002227}
2228
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002229void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002230 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002231 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2232 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2233 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002234 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2235 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002236 OMPLoc);
2237 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2238 // to register constructor/destructor for variable.
2239 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002240 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2241 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002242 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002243 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002244 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002245}
2246
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002247llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002248 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002249 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002250 if (CGM.getLangOpts().OpenMPUseTLS &&
2251 CGM.getContext().getTargetInfo().isTLSSupported())
2252 return nullptr;
2253
Alexey Bataev97720002014-11-11 04:05:39 +00002254 VD = VD->getDefinition(CGM.getContext());
2255 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2256 ThreadPrivateWithDefinition.insert(VD);
2257 QualType ASTTy = VD->getType();
2258
2259 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2260 auto Init = VD->getAnyInitializer();
2261 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2262 // Generate function that re-emits the declaration's initializer into the
2263 // threadprivate copy of the variable VD
2264 CodeGenFunction CtorCGF(CGM);
2265 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002266 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2267 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002268 Args.push_back(&Dst);
2269
John McCallc56a8b32016-03-11 04:30:31 +00002270 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2271 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002272 auto FTy = CGM.getTypes().GetFunctionType(FI);
2273 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002274 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002275 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2276 Args, SourceLocation());
2277 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002278 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002279 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002280 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2281 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2282 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002283 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2284 /*IsInitializer=*/true);
2285 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002286 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002287 CGM.getContext().VoidPtrTy, Dst.getLocation());
2288 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2289 CtorCGF.FinishFunction();
2290 Ctor = Fn;
2291 }
2292 if (VD->getType().isDestructedType() != QualType::DK_none) {
2293 // Generate function that emits destructor call for the threadprivate copy
2294 // of the variable VD
2295 CodeGenFunction DtorCGF(CGM);
2296 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002297 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2298 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002299 Args.push_back(&Dst);
2300
John McCallc56a8b32016-03-11 04:30:31 +00002301 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2302 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002303 auto FTy = CGM.getTypes().GetFunctionType(FI);
2304 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002305 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002306 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002307 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2308 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002309 // Create a scope with an artificial location for the body of this function.
2310 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002311 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2312 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002313 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2314 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002315 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2316 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2317 DtorCGF.FinishFunction();
2318 Dtor = Fn;
2319 }
2320 // Do not emit init function if it is not required.
2321 if (!Ctor && !Dtor)
2322 return nullptr;
2323
2324 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2325 auto CopyCtorTy =
2326 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2327 /*isVarArg=*/false)->getPointerTo();
2328 // Copying constructor for the threadprivate variable.
2329 // Must be NULL - reserved by runtime, but currently it requires that this
2330 // parameter is always NULL. Otherwise it fires assertion.
2331 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2332 if (Ctor == nullptr) {
2333 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2334 /*isVarArg=*/false)->getPointerTo();
2335 Ctor = llvm::Constant::getNullValue(CtorTy);
2336 }
2337 if (Dtor == nullptr) {
2338 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2339 /*isVarArg=*/false)->getPointerTo();
2340 Dtor = llvm::Constant::getNullValue(DtorTy);
2341 }
2342 if (!CGF) {
2343 auto InitFunctionTy =
2344 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2345 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002346 InitFunctionTy, ".__omp_threadprivate_init_.",
2347 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002348 CodeGenFunction InitCGF(CGM);
2349 FunctionArgList ArgList;
2350 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2351 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2352 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002353 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002354 InitCGF.FinishFunction();
2355 return InitFunction;
2356 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002357 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002358 }
2359 return nullptr;
2360}
2361
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002362Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2363 QualType VarType,
2364 StringRef Name) {
2365 llvm::Twine VarName(Name, ".artificial.");
2366 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2367 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2368 llvm::Value *Args[] = {
2369 emitUpdateLocation(CGF, SourceLocation()),
2370 getThreadID(CGF, SourceLocation()),
2371 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2372 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2373 /*IsSigned=*/false),
2374 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2375 return Address(
2376 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2377 CGF.EmitRuntimeCall(
2378 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2379 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2380 CGM.getPointerAlign());
2381}
2382
Alexey Bataev1d677132015-04-22 13:57:31 +00002383/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2384/// function. Here is the logic:
2385/// if (Cond) {
2386/// ThenGen();
2387/// } else {
2388/// ElseGen();
2389/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002390void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2391 const RegionCodeGenTy &ThenGen,
2392 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002393 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2394
2395 // If the condition constant folds and can be elided, try to avoid emitting
2396 // the condition and the dead arm of the if/else.
2397 bool CondConstant;
2398 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002399 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002400 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002401 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002402 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002403 return;
2404 }
2405
2406 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2407 // emit the conditional branch.
2408 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2409 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2410 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2411 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2412
2413 // Emit the 'then' code.
2414 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002415 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002416 CGF.EmitBranch(ContBlock);
2417 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002418 // There is no need to emit line number for unconditional branch.
2419 (void)ApplyDebugLocation::CreateEmpty(CGF);
2420 CGF.EmitBlock(ElseBlock);
2421 ElseGen(CGF);
2422 // There is no need to emit line number for unconditional branch.
2423 (void)ApplyDebugLocation::CreateEmpty(CGF);
2424 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002425 // Emit the continuation block for code after the if.
2426 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002427}
2428
Alexey Bataev1d677132015-04-22 13:57:31 +00002429void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2430 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002431 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002432 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002433 if (!CGF.HaveInsertPoint())
2434 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002435 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002436 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2437 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002438 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002439 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002440 llvm::Value *Args[] = {
2441 RTLoc,
2442 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002443 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002444 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2445 RealArgs.append(std::begin(Args), std::end(Args));
2446 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2447
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002448 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002449 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2450 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002451 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2452 PrePostActionTy &) {
2453 auto &RT = CGF.CGM.getOpenMPRuntime();
2454 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002455 // Build calls:
2456 // __kmpc_serialized_parallel(&Loc, GTid);
2457 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002458 CGF.EmitRuntimeCall(
2459 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002460
Alexey Bataev1d677132015-04-22 13:57:31 +00002461 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002462 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002463 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002464 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2465 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002466 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002467 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2468 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2469 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2470 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002471 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002472
Alexey Bataev1d677132015-04-22 13:57:31 +00002473 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002474 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002475 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002476 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2477 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002478 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002479 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002480 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002481 else {
2482 RegionCodeGenTy ThenRCG(ThenGen);
2483 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002484 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002485}
2486
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002487// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002488// thread-ID variable (it is passed in a first argument of the outlined function
2489// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2490// regular serial code region, get thread ID by calling kmp_int32
2491// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2492// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002493Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2494 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002495 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002496 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002497 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002498 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002499
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002500 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002501 auto Int32Ty =
2502 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2503 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2504 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002505 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002506
2507 return ThreadIDTemp;
2508}
2509
Alexey Bataev97720002014-11-11 04:05:39 +00002510llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002511CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002512 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002513 SmallString<256> Buffer;
2514 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002515 Out << Name;
2516 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002517 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2518 if (Elem.second) {
2519 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002520 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002521 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002522 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002523
David Blaikie13156b62014-11-19 03:06:06 +00002524 return Elem.second = new llvm::GlobalVariable(
2525 CGM.getModule(), Ty, /*IsConstant*/ false,
2526 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2527 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002528}
2529
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002530llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002531 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002532 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002533}
2534
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002535namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002536/// Common pre(post)-action for different OpenMP constructs.
2537class CommonActionTy final : public PrePostActionTy {
2538 llvm::Value *EnterCallee;
2539 ArrayRef<llvm::Value *> EnterArgs;
2540 llvm::Value *ExitCallee;
2541 ArrayRef<llvm::Value *> ExitArgs;
2542 bool Conditional;
2543 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002544
2545public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002546 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2547 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2548 bool Conditional = false)
2549 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2550 ExitArgs(ExitArgs), Conditional(Conditional) {}
2551 void Enter(CodeGenFunction &CGF) override {
2552 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2553 if (Conditional) {
2554 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2555 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2556 ContBlock = CGF.createBasicBlock("omp_if.end");
2557 // Generate the branch (If-stmt)
2558 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2559 CGF.EmitBlock(ThenBlock);
2560 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002561 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002562 void Done(CodeGenFunction &CGF) {
2563 // Emit the rest of blocks/branches
2564 CGF.EmitBranch(ContBlock);
2565 CGF.EmitBlock(ContBlock, true);
2566 }
2567 void Exit(CodeGenFunction &CGF) override {
2568 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002569 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002570};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002571} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002572
2573void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2574 StringRef CriticalName,
2575 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002576 SourceLocation Loc, const Expr *Hint) {
2577 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002578 // CriticalOpGen();
2579 // __kmpc_end_critical(ident_t *, gtid, Lock);
2580 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002581 if (!CGF.HaveInsertPoint())
2582 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002583 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2584 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002585 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2586 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002587 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002588 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2589 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2590 }
2591 CommonActionTy Action(
2592 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2593 : OMPRTL__kmpc_critical),
2594 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2595 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002596 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002597}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002598
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002599void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002600 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002601 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002602 if (!CGF.HaveInsertPoint())
2603 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002604 // if(__kmpc_master(ident_t *, gtid)) {
2605 // MasterOpGen();
2606 // __kmpc_end_master(ident_t *, gtid);
2607 // }
2608 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002609 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002610 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2611 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2612 /*Conditional=*/true);
2613 MasterOpGen.setAction(Action);
2614 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2615 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002616}
2617
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002618void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2619 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002620 if (!CGF.HaveInsertPoint())
2621 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002622 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2623 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002624 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002625 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002626 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002627 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2628 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002629}
2630
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002631void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2632 const RegionCodeGenTy &TaskgroupOpGen,
2633 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002634 if (!CGF.HaveInsertPoint())
2635 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002636 // __kmpc_taskgroup(ident_t *, gtid);
2637 // TaskgroupOpGen();
2638 // __kmpc_end_taskgroup(ident_t *, gtid);
2639 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002640 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2641 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2642 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2643 Args);
2644 TaskgroupOpGen.setAction(Action);
2645 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002646}
2647
John McCall7f416cc2015-09-08 08:05:57 +00002648/// Given an array of pointers to variables, project the address of a
2649/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002650static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2651 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002652 // Pull out the pointer to the variable.
2653 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002654 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002655 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2656
2657 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002658 Addr = CGF.Builder.CreateElementBitCast(
2659 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002660 return Addr;
2661}
2662
Alexey Bataeva63048e2015-03-23 06:18:07 +00002663static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002664 CodeGenModule &CGM, llvm::Type *ArgsType,
2665 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2666 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002667 auto &C = CGM.getContext();
2668 // void copy_func(void *LHSArg, void *RHSArg);
2669 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002670 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2671 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002672 Args.push_back(&LHSArg);
2673 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002674 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002675 auto *Fn = llvm::Function::Create(
2676 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2677 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002678 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002679 CodeGenFunction CGF(CGM);
2680 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002681 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002682 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002683 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2684 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2685 ArgsType), CGF.getPointerAlign());
2686 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2687 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2688 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002689 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2690 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2691 // ...
2692 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002693 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002694 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2695 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2696
2697 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2698 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2699
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002700 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2701 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002702 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002703 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002704 CGF.FinishFunction();
2705 return Fn;
2706}
2707
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002708void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002709 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002710 SourceLocation Loc,
2711 ArrayRef<const Expr *> CopyprivateVars,
2712 ArrayRef<const Expr *> SrcExprs,
2713 ArrayRef<const Expr *> DstExprs,
2714 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002715 if (!CGF.HaveInsertPoint())
2716 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002717 assert(CopyprivateVars.size() == SrcExprs.size() &&
2718 CopyprivateVars.size() == DstExprs.size() &&
2719 CopyprivateVars.size() == AssignmentOps.size());
2720 auto &C = CGM.getContext();
2721 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002722 // if(__kmpc_single(ident_t *, gtid)) {
2723 // SingleOpGen();
2724 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002725 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002726 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002727 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2728 // <copy_func>, did_it);
2729
John McCall7f416cc2015-09-08 08:05:57 +00002730 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002731 if (!CopyprivateVars.empty()) {
2732 // int32 did_it = 0;
2733 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2734 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002735 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002736 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002737 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002738 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002739 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2740 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2741 /*Conditional=*/true);
2742 SingleOpGen.setAction(Action);
2743 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2744 if (DidIt.isValid()) {
2745 // did_it = 1;
2746 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2747 }
2748 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002749 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2750 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002751 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002752 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2753 auto CopyprivateArrayTy =
2754 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2755 /*IndexTypeQuals=*/0);
2756 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002757 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002758 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2759 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002760 Address Elem = CGF.Builder.CreateConstArrayGEP(
2761 CopyprivateList, I, CGF.getPointerSize());
2762 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002763 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002764 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2765 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002766 }
2767 // Build function that copies private values from single region to all other
2768 // threads in the corresponding parallel region.
2769 auto *CpyFn = emitCopyprivateCopyFunction(
2770 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002771 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002772 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002773 Address CL =
2774 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2775 CGF.VoidPtrTy);
2776 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002777 llvm::Value *Args[] = {
2778 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2779 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002780 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002781 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002782 CpyFn, // void (*) (void *, void *) <copy_func>
2783 DidItVal // i32 did_it
2784 };
2785 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2786 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002787}
2788
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002789void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2790 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002791 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002792 if (!CGF.HaveInsertPoint())
2793 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002794 // __kmpc_ordered(ident_t *, gtid);
2795 // OrderedOpGen();
2796 // __kmpc_end_ordered(ident_t *, gtid);
2797 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002798 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002799 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002800 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2801 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2802 Args);
2803 OrderedOpGen.setAction(Action);
2804 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2805 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002806 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002807 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002808}
2809
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002810void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002811 OpenMPDirectiveKind Kind, bool EmitChecks,
2812 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002813 if (!CGF.HaveInsertPoint())
2814 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002815 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002816 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002817 unsigned Flags;
2818 if (Kind == OMPD_for)
2819 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2820 else if (Kind == OMPD_sections)
2821 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2822 else if (Kind == OMPD_single)
2823 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2824 else if (Kind == OMPD_barrier)
2825 Flags = OMP_IDENT_BARRIER_EXPL;
2826 else
2827 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002828 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2829 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002830 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2831 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002832 if (auto *OMPRegionInfo =
2833 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002834 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002835 auto *Result = CGF.EmitRuntimeCall(
2836 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002837 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002838 // if (__kmpc_cancel_barrier()) {
2839 // exit from construct;
2840 // }
2841 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2842 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2843 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2844 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2845 CGF.EmitBlock(ExitBB);
2846 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002847 auto CancelDestination =
2848 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002849 CGF.EmitBranchThroughCleanup(CancelDestination);
2850 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2851 }
2852 return;
2853 }
2854 }
2855 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002856}
2857
Alexander Musmanc6388682014-12-15 07:07:06 +00002858/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2859static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002860 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002861 switch (ScheduleKind) {
2862 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002863 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2864 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002865 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002866 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002867 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002868 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002869 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002870 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2871 case OMPC_SCHEDULE_auto:
2872 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002873 case OMPC_SCHEDULE_unknown:
2874 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002875 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002876 }
2877 llvm_unreachable("Unexpected runtime schedule");
2878}
2879
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002880/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2881static OpenMPSchedType
2882getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2883 // only static is allowed for dist_schedule
2884 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2885}
2886
Alexander Musmanc6388682014-12-15 07:07:06 +00002887bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2888 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002889 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002890 return Schedule == OMP_sch_static;
2891}
2892
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002893bool CGOpenMPRuntime::isStaticNonchunked(
2894 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2895 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2896 return Schedule == OMP_dist_sch_static;
2897}
2898
2899
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002900bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002901 auto Schedule =
2902 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002903 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2904 return Schedule != OMP_sch_static;
2905}
2906
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002907static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2908 OpenMPScheduleClauseModifier M1,
2909 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002910 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002911 switch (M1) {
2912 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002913 Modifier = OMP_sch_modifier_monotonic;
2914 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002915 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002916 Modifier = OMP_sch_modifier_nonmonotonic;
2917 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002918 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002919 if (Schedule == OMP_sch_static_chunked)
2920 Schedule = OMP_sch_static_balanced_chunked;
2921 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002922 case OMPC_SCHEDULE_MODIFIER_last:
2923 case OMPC_SCHEDULE_MODIFIER_unknown:
2924 break;
2925 }
2926 switch (M2) {
2927 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002928 Modifier = OMP_sch_modifier_monotonic;
2929 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002930 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002931 Modifier = OMP_sch_modifier_nonmonotonic;
2932 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002933 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002934 if (Schedule == OMP_sch_static_chunked)
2935 Schedule = OMP_sch_static_balanced_chunked;
2936 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002937 case OMPC_SCHEDULE_MODIFIER_last:
2938 case OMPC_SCHEDULE_MODIFIER_unknown:
2939 break;
2940 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002941 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002942}
2943
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002944void CGOpenMPRuntime::emitForDispatchInit(
2945 CodeGenFunction &CGF, SourceLocation Loc,
2946 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2947 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002948 if (!CGF.HaveInsertPoint())
2949 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002950 OpenMPSchedType Schedule = getRuntimeSchedule(
2951 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002952 assert(Ordered ||
2953 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002954 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2955 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002956 // Call __kmpc_dispatch_init(
2957 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2958 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2959 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002960
John McCall7f416cc2015-09-08 08:05:57 +00002961 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002962 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2963 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002964 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002965 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2966 CGF.Builder.getInt32(addMonoNonMonoModifier(
2967 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002968 DispatchValues.LB, // Lower
2969 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002970 CGF.Builder.getIntN(IVSize, 1), // Stride
2971 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002972 };
2973 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2974}
2975
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002976static void emitForStaticInitCall(
2977 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2978 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2979 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002980 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002981 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002982 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002983
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002984 assert(!Values.Ordered);
2985 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2986 Schedule == OMP_sch_static_balanced_chunked ||
2987 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2988 Schedule == OMP_dist_sch_static ||
2989 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002990
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002991 // Call __kmpc_for_static_init(
2992 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2993 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2994 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2995 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2996 llvm::Value *Chunk = Values.Chunk;
2997 if (Chunk == nullptr) {
2998 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2999 Schedule == OMP_dist_sch_static) &&
3000 "expected static non-chunked schedule");
3001 // If the Chunk was not specified in the clause - use default value 1.
3002 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3003 } else {
3004 assert((Schedule == OMP_sch_static_chunked ||
3005 Schedule == OMP_sch_static_balanced_chunked ||
3006 Schedule == OMP_ord_static_chunked ||
3007 Schedule == OMP_dist_sch_static_chunked) &&
3008 "expected static chunked schedule");
3009 }
3010 llvm::Value *Args[] = {
3011 UpdateLocation,
3012 ThreadId,
3013 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3014 M2)), // Schedule type
3015 Values.IL.getPointer(), // &isLastIter
3016 Values.LB.getPointer(), // &LB
3017 Values.UB.getPointer(), // &UB
3018 Values.ST.getPointer(), // &Stride
3019 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3020 Chunk // Chunk
3021 };
3022 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003023}
3024
John McCall7f416cc2015-09-08 08:05:57 +00003025void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3026 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003027 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003028 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003029 const StaticRTInput &Values) {
3030 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3031 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3032 assert(isOpenMPWorksharingDirective(DKind) &&
3033 "Expected loop-based or sections-based directive.");
3034 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3035 isOpenMPLoopDirective(DKind)
3036 ? OMP_IDENT_WORK_LOOP
3037 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003038 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003039 auto *StaticInitFunction =
3040 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003041 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003042 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003043}
John McCall7f416cc2015-09-08 08:05:57 +00003044
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003045void CGOpenMPRuntime::emitDistributeStaticInit(
3046 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003047 OpenMPDistScheduleClauseKind SchedKind,
3048 const CGOpenMPRuntime::StaticRTInput &Values) {
3049 OpenMPSchedType ScheduleNum =
3050 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3051 auto *UpdatedLocation =
3052 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003053 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003054 auto *StaticInitFunction =
3055 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003056 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3057 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003058 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003059}
3060
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003061void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
3062 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003063 if (!CGF.HaveInsertPoint())
3064 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003065 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003066 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003067 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3068 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003069}
3070
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003071void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3072 SourceLocation Loc,
3073 unsigned IVSize,
3074 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003075 if (!CGF.HaveInsertPoint())
3076 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003077 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003078 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003079 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3080}
3081
Alexander Musman92bdaab2015-03-12 13:37:50 +00003082llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3083 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003084 bool IVSigned, Address IL,
3085 Address LB, Address UB,
3086 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003087 // Call __kmpc_dispatch_next(
3088 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3089 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3090 // kmp_int[32|64] *p_stride);
3091 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003092 emitUpdateLocation(CGF, Loc),
3093 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003094 IL.getPointer(), // &isLastIter
3095 LB.getPointer(), // &Lower
3096 UB.getPointer(), // &Upper
3097 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003098 };
3099 llvm::Value *Call =
3100 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3101 return CGF.EmitScalarConversion(
3102 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003103 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003104}
3105
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003106void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3107 llvm::Value *NumThreads,
3108 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003109 if (!CGF.HaveInsertPoint())
3110 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003111 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3112 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003113 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003114 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003115 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3116 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003117}
3118
Alexey Bataev7f210c62015-06-18 13:40:03 +00003119void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3120 OpenMPProcBindClauseKind ProcBind,
3121 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003122 if (!CGF.HaveInsertPoint())
3123 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003124 // Constants for proc bind value accepted by the runtime.
3125 enum ProcBindTy {
3126 ProcBindFalse = 0,
3127 ProcBindTrue,
3128 ProcBindMaster,
3129 ProcBindClose,
3130 ProcBindSpread,
3131 ProcBindIntel,
3132 ProcBindDefault
3133 } RuntimeProcBind;
3134 switch (ProcBind) {
3135 case OMPC_PROC_BIND_master:
3136 RuntimeProcBind = ProcBindMaster;
3137 break;
3138 case OMPC_PROC_BIND_close:
3139 RuntimeProcBind = ProcBindClose;
3140 break;
3141 case OMPC_PROC_BIND_spread:
3142 RuntimeProcBind = ProcBindSpread;
3143 break;
3144 case OMPC_PROC_BIND_unknown:
3145 llvm_unreachable("Unsupported proc_bind value.");
3146 }
3147 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3148 llvm::Value *Args[] = {
3149 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3150 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3151 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3152}
3153
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003154void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3155 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003156 if (!CGF.HaveInsertPoint())
3157 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003158 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003159 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3160 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003161}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003162
Alexey Bataev62b63b12015-03-10 07:28:44 +00003163namespace {
3164/// \brief Indexes of fields for type kmp_task_t.
3165enum KmpTaskTFields {
3166 /// \brief List of shared variables.
3167 KmpTaskTShareds,
3168 /// \brief Task routine.
3169 KmpTaskTRoutine,
3170 /// \brief Partition id for the untied tasks.
3171 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003172 /// Function with call of destructors for private variables.
3173 Data1,
3174 /// Task priority.
3175 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003176 /// (Taskloops only) Lower bound.
3177 KmpTaskTLowerBound,
3178 /// (Taskloops only) Upper bound.
3179 KmpTaskTUpperBound,
3180 /// (Taskloops only) Stride.
3181 KmpTaskTStride,
3182 /// (Taskloops only) Is last iteration flag.
3183 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003184 /// (Taskloops only) Reduction data.
3185 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003186};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003187} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003188
Samuel Antaoee8fb302016-01-06 13:42:12 +00003189bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3190 // FIXME: Add other entries type when they become supported.
3191 return OffloadEntriesTargetRegion.empty();
3192}
3193
3194/// \brief Initialize target region entry.
3195void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3196 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3197 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003198 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003199 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3200 "only required for the device "
3201 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003202 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003203 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3204 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003205 ++OffloadingEntriesNum;
3206}
3207
3208void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3209 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3210 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003211 llvm::Constant *Addr, llvm::Constant *ID,
3212 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003213 // If we are emitting code for a target, the entry is already initialized,
3214 // only has to be registered.
3215 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003216 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003217 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003218 auto &Entry =
3219 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003220 assert(Entry.isValid() && "Entry not initialized!");
3221 Entry.setAddress(Addr);
3222 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003223 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003224 return;
3225 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003226 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003227 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003228 }
3229}
3230
3231bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003232 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3233 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003234 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3235 if (PerDevice == OffloadEntriesTargetRegion.end())
3236 return false;
3237 auto PerFile = PerDevice->second.find(FileID);
3238 if (PerFile == PerDevice->second.end())
3239 return false;
3240 auto PerParentName = PerFile->second.find(ParentName);
3241 if (PerParentName == PerFile->second.end())
3242 return false;
3243 auto PerLine = PerParentName->second.find(LineNum);
3244 if (PerLine == PerParentName->second.end())
3245 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003246 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003247 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003248 return false;
3249 return true;
3250}
3251
3252void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3253 const OffloadTargetRegionEntryInfoActTy &Action) {
3254 // Scan all target region entries and perform the provided action.
3255 for (auto &D : OffloadEntriesTargetRegion)
3256 for (auto &F : D.second)
3257 for (auto &P : F.second)
3258 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003259 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003260}
3261
3262/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3263/// \a Codegen. This is used to emit the two functions that register and
3264/// unregister the descriptor of the current compilation unit.
3265static llvm::Function *
3266createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3267 const RegionCodeGenTy &Codegen) {
3268 auto &C = CGM.getContext();
3269 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003270 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003271 Args.push_back(&DummyPtr);
3272
3273 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003274 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003275 auto FTy = CGM.getTypes().GetFunctionType(FI);
3276 auto *Fn =
3277 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3278 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3279 Codegen(CGF);
3280 CGF.FinishFunction();
3281 return Fn;
3282}
3283
3284llvm::Function *
3285CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3286
3287 // If we don't have entries or if we are emitting code for the device, we
3288 // don't need to do anything.
3289 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3290 return nullptr;
3291
3292 auto &M = CGM.getModule();
3293 auto &C = CGM.getContext();
3294
3295 // Get list of devices we care about
3296 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3297
3298 // We should be creating an offloading descriptor only if there are devices
3299 // specified.
3300 assert(!Devices.empty() && "No OpenMP offloading devices??");
3301
3302 // Create the external variables that will point to the begin and end of the
3303 // host entries section. These will be defined by the linker.
3304 auto *OffloadEntryTy =
3305 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3306 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3307 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003308 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003309 ".omp_offloading.entries_begin");
3310 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3311 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003312 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003313 ".omp_offloading.entries_end");
3314
3315 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003316 auto *DeviceImageTy = cast<llvm::StructType>(
3317 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003318 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003319 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003320
3321 for (unsigned i = 0; i < Devices.size(); ++i) {
3322 StringRef T = Devices[i].getTriple();
3323 auto *ImgBegin = new llvm::GlobalVariable(
3324 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003325 /*Initializer=*/nullptr,
3326 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003327 auto *ImgEnd = new llvm::GlobalVariable(
3328 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003329 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003330
John McCall6c9f1fdb2016-11-19 08:17:24 +00003331 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3332 Dev.add(ImgBegin);
3333 Dev.add(ImgEnd);
3334 Dev.add(HostEntriesBegin);
3335 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003336 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003337 }
3338
3339 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003340 llvm::GlobalVariable *DeviceImages =
3341 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3342 CGM.getPointerAlign(),
3343 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003344 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003345
3346 // This is a Zero array to be used in the creation of the constant expressions
3347 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3348 llvm::Constant::getNullValue(CGM.Int32Ty)};
3349
3350 // Create the target region descriptor.
3351 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3352 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003353 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003354 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3355 DescInit.addInt(CGM.Int32Ty, Devices.size());
3356 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3357 DeviceImages,
3358 Index));
3359 DescInit.add(HostEntriesBegin);
3360 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003361
John McCall6c9f1fdb2016-11-19 08:17:24 +00003362 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3363 CGM.getPointerAlign(),
3364 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003365
3366 // Emit code to register or unregister the descriptor at execution
3367 // startup or closing, respectively.
3368
3369 // Create a variable to drive the registration and unregistration of the
3370 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3371 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3372 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003373 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003374
3375 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003376 CGM, ".omp_offloading.descriptor_unreg",
3377 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003378 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3379 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003380 });
3381 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003382 CGM, ".omp_offloading.descriptor_reg",
3383 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003384 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3385 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003386 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3387 });
George Rokos29d0f002017-05-27 03:03:13 +00003388 if (CGM.supportsCOMDAT()) {
3389 // It is sufficient to call registration function only once, so create a
3390 // COMDAT group for registration/unregistration functions and associated
3391 // data. That would reduce startup time and code size. Registration
3392 // function serves as a COMDAT group key.
3393 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3394 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3395 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3396 RegFn->setComdat(ComdatKey);
3397 UnRegFn->setComdat(ComdatKey);
3398 DeviceImages->setComdat(ComdatKey);
3399 Desc->setComdat(ComdatKey);
3400 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003401 return RegFn;
3402}
3403
Samuel Antao2de62b02016-02-13 23:35:10 +00003404void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003405 llvm::Constant *Addr, uint64_t Size,
3406 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003407 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003408 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3409 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3410 llvm::LLVMContext &C = CGM.getModule().getContext();
3411 llvm::Module &M = CGM.getModule();
3412
3413 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003414 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003415
3416 // Create constant string with the name.
3417 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3418
3419 llvm::GlobalVariable *Str =
3420 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3421 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3422 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003423 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003424 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3425
John McCall6c9f1fdb2016-11-19 08:17:24 +00003426 // We can't have any padding between symbols, so we need to have 1-byte
3427 // alignment.
3428 auto Align = CharUnits::fromQuantity(1);
3429
Samuel Antaoee8fb302016-01-06 13:42:12 +00003430 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003431 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003432 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3433 EntryInit.add(AddrPtr);
3434 EntryInit.add(StrPtr);
3435 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003436 EntryInit.addInt(CGM.Int32Ty, Flags);
3437 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003438 llvm::GlobalVariable *Entry =
3439 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3440 Align,
3441 /*constant*/ true,
3442 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003443
3444 // The entry has to be created in the section the linker expects it to be.
3445 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003446}
3447
3448void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3449 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003450 // can easily figure out what to emit. The produced metadata looks like
3451 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003452 //
3453 // !omp_offload.info = !{!1, ...}
3454 //
3455 // Right now we only generate metadata for function that contain target
3456 // regions.
3457
3458 // If we do not have entries, we dont need to do anything.
3459 if (OffloadEntriesInfoManager.empty())
3460 return;
3461
3462 llvm::Module &M = CGM.getModule();
3463 llvm::LLVMContext &C = M.getContext();
3464 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3465 OrderedEntries(OffloadEntriesInfoManager.size());
3466
3467 // Create the offloading info metadata node.
3468 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3469
Simon Pilgrim2c518802017-03-30 14:13:19 +00003470 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003471 auto getMDInt = [&](unsigned v) {
3472 return llvm::ConstantAsMetadata::get(
3473 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3474 };
3475
3476 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3477
3478 // Create function that emits metadata for each target region entry;
3479 auto &&TargetRegionMetadataEmitter = [&](
3480 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003481 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3482 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3483 // Generate metadata for target regions. Each entry of this metadata
3484 // contains:
3485 // - Entry 0 -> Kind of this type of metadata (0).
3486 // - Entry 1 -> Device ID of the file where the entry was identified.
3487 // - Entry 2 -> File ID of the file where the entry was identified.
3488 // - Entry 3 -> Mangled name of the function where the entry was identified.
3489 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003490 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003491 // The first element of the metadata node is the kind.
3492 Ops.push_back(getMDInt(E.getKind()));
3493 Ops.push_back(getMDInt(DeviceID));
3494 Ops.push_back(getMDInt(FileID));
3495 Ops.push_back(getMDString(ParentName));
3496 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003497 Ops.push_back(getMDInt(E.getOrder()));
3498
3499 // Save this entry in the right position of the ordered entries array.
3500 OrderedEntries[E.getOrder()] = &E;
3501
3502 // Add metadata to the named metadata node.
3503 MD->addOperand(llvm::MDNode::get(C, Ops));
3504 };
3505
3506 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3507 TargetRegionMetadataEmitter);
3508
3509 for (auto *E : OrderedEntries) {
3510 assert(E && "All ordered entries must exist!");
3511 if (auto *CE =
3512 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3513 E)) {
3514 assert(CE->getID() && CE->getAddress() &&
3515 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003516 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003517 } else
3518 llvm_unreachable("Unsupported entry kind.");
3519 }
3520}
3521
3522/// \brief Loads all the offload entries information from the host IR
3523/// metadata.
3524void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3525 // If we are in target mode, load the metadata from the host IR. This code has
3526 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3527
3528 if (!CGM.getLangOpts().OpenMPIsDevice)
3529 return;
3530
3531 if (CGM.getLangOpts().OMPHostIRFile.empty())
3532 return;
3533
3534 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3535 if (Buf.getError())
3536 return;
3537
3538 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003539 auto ME = expectedToErrorOrAndEmitErrors(
3540 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003541
3542 if (ME.getError())
3543 return;
3544
3545 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3546 if (!MD)
3547 return;
3548
3549 for (auto I : MD->operands()) {
3550 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3551
3552 auto getMDInt = [&](unsigned Idx) {
3553 llvm::ConstantAsMetadata *V =
3554 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3555 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3556 };
3557
3558 auto getMDString = [&](unsigned Idx) {
3559 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3560 return V->getString();
3561 };
3562
3563 switch (getMDInt(0)) {
3564 default:
3565 llvm_unreachable("Unexpected metadata!");
3566 break;
3567 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3568 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3569 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3570 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3571 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003572 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003573 break;
3574 }
3575 }
3576}
3577
Alexey Bataev62b63b12015-03-10 07:28:44 +00003578void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3579 if (!KmpRoutineEntryPtrTy) {
3580 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3581 auto &C = CGM.getContext();
3582 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3583 FunctionProtoType::ExtProtoInfo EPI;
3584 KmpRoutineEntryPtrQTy = C.getPointerType(
3585 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3586 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3587 }
3588}
3589
Alexey Bataevc71a4092015-09-11 10:29:41 +00003590static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3591 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003592 auto *Field = FieldDecl::Create(
3593 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3594 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3595 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3596 Field->setAccess(AS_public);
3597 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003598 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003599}
3600
Samuel Antaoee8fb302016-01-06 13:42:12 +00003601QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3602
3603 // Make sure the type of the entry is already created. This is the type we
3604 // have to create:
3605 // struct __tgt_offload_entry{
3606 // void *addr; // Pointer to the offload entry info.
3607 // // (function or global)
3608 // char *name; // Name of the function or global.
3609 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003610 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3611 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003612 // };
3613 if (TgtOffloadEntryQTy.isNull()) {
3614 ASTContext &C = CGM.getContext();
3615 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3616 RD->startDefinition();
3617 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3618 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3619 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003620 addFieldToRecordDecl(
3621 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3622 addFieldToRecordDecl(
3623 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003624 RD->completeDefinition();
3625 TgtOffloadEntryQTy = C.getRecordType(RD);
3626 }
3627 return TgtOffloadEntryQTy;
3628}
3629
3630QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3631 // These are the types we need to build:
3632 // struct __tgt_device_image{
3633 // void *ImageStart; // Pointer to the target code start.
3634 // void *ImageEnd; // Pointer to the target code end.
3635 // // We also add the host entries to the device image, as it may be useful
3636 // // for the target runtime to have access to that information.
3637 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3638 // // the entries.
3639 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3640 // // entries (non inclusive).
3641 // };
3642 if (TgtDeviceImageQTy.isNull()) {
3643 ASTContext &C = CGM.getContext();
3644 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3645 RD->startDefinition();
3646 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3647 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3648 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3649 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3650 RD->completeDefinition();
3651 TgtDeviceImageQTy = C.getRecordType(RD);
3652 }
3653 return TgtDeviceImageQTy;
3654}
3655
3656QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3657 // struct __tgt_bin_desc{
3658 // int32_t NumDevices; // Number of devices supported.
3659 // __tgt_device_image *DeviceImages; // Arrays of device images
3660 // // (one per device).
3661 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3662 // // entries.
3663 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3664 // // entries (non inclusive).
3665 // };
3666 if (TgtBinaryDescriptorQTy.isNull()) {
3667 ASTContext &C = CGM.getContext();
3668 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3669 RD->startDefinition();
3670 addFieldToRecordDecl(
3671 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3672 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3673 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3674 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3675 RD->completeDefinition();
3676 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3677 }
3678 return TgtBinaryDescriptorQTy;
3679}
3680
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003681namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003682struct PrivateHelpersTy {
3683 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3684 const VarDecl *PrivateElemInit)
3685 : Original(Original), PrivateCopy(PrivateCopy),
3686 PrivateElemInit(PrivateElemInit) {}
3687 const VarDecl *Original;
3688 const VarDecl *PrivateCopy;
3689 const VarDecl *PrivateElemInit;
3690};
3691typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003692} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003693
Alexey Bataev9e034042015-05-05 04:05:12 +00003694static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003695createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003696 if (!Privates.empty()) {
3697 auto &C = CGM.getContext();
3698 // Build struct .kmp_privates_t. {
3699 // /* private vars */
3700 // };
3701 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3702 RD->startDefinition();
3703 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003704 auto *VD = Pair.second.Original;
3705 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003706 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003707 auto *FD = addFieldToRecordDecl(C, RD, Type);
3708 if (VD->hasAttrs()) {
3709 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3710 E(VD->getAttrs().end());
3711 I != E; ++I)
3712 FD->addAttr(*I);
3713 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003714 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003715 RD->completeDefinition();
3716 return RD;
3717 }
3718 return nullptr;
3719}
3720
Alexey Bataev9e034042015-05-05 04:05:12 +00003721static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003722createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3723 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003724 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003725 auto &C = CGM.getContext();
3726 // Build struct kmp_task_t {
3727 // void * shareds;
3728 // kmp_routine_entry_t routine;
3729 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003730 // kmp_cmplrdata_t data1;
3731 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003732 // For taskloops additional fields:
3733 // kmp_uint64 lb;
3734 // kmp_uint64 ub;
3735 // kmp_int64 st;
3736 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003737 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003738 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003739 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3740 UD->startDefinition();
3741 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3742 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3743 UD->completeDefinition();
3744 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003745 auto *RD = C.buildImplicitRecord("kmp_task_t");
3746 RD->startDefinition();
3747 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3748 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3749 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003750 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3751 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003752 if (isOpenMPTaskLoopDirective(Kind)) {
3753 QualType KmpUInt64Ty =
3754 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3755 QualType KmpInt64Ty =
3756 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3757 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3758 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3759 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3760 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003761 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003762 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003763 RD->completeDefinition();
3764 return RD;
3765}
3766
3767static RecordDecl *
3768createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003769 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003770 auto &C = CGM.getContext();
3771 // Build struct kmp_task_t_with_privates {
3772 // kmp_task_t task_data;
3773 // .kmp_privates_t. privates;
3774 // };
3775 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3776 RD->startDefinition();
3777 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003778 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3779 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3780 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003781 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003782 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003783}
3784
3785/// \brief Emit a proxy function which accepts kmp_task_t as the second
3786/// argument.
3787/// \code
3788/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003789/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003790/// For taskloops:
3791/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003792/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003793/// return 0;
3794/// }
3795/// \endcode
3796static llvm::Value *
3797emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003798 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3799 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003800 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003801 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3802 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003803 auto &C = CGM.getContext();
3804 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003805 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3806 ImplicitParamDecl::Other);
3807 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3808 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3809 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003810 Args.push_back(&GtidArg);
3811 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003812 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003813 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003814 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3815 auto *TaskEntry =
3816 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3817 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003818 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003819 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003820 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3821
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003822 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003823 // tt,
3824 // For taskloops:
3825 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3826 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003827 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003828 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003829 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3830 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3831 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003832 auto *KmpTaskTWithPrivatesQTyRD =
3833 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003834 LValue Base =
3835 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003836 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3837 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3838 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003839 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003840
3841 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3842 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003843 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003844 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003845 CGF.ConvertTypeForMem(SharedsPtrTy));
3846
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003847 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3848 llvm::Value *PrivatesParam;
3849 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3850 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3851 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003852 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003853 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003854 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003855
Alexey Bataev7292c292016-04-25 12:22:29 +00003856 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3857 TaskPrivatesMap,
3858 CGF.Builder
3859 .CreatePointerBitCastOrAddrSpaceCast(
3860 TDBase.getAddress(), CGF.VoidPtrTy)
3861 .getPointer()};
3862 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3863 std::end(CommonArgs));
3864 if (isOpenMPTaskLoopDirective(Kind)) {
3865 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3866 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3867 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3868 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3869 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3870 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3871 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3872 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3873 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3874 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3875 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3876 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003877 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3878 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3879 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003880 CallArgs.push_back(LBParam);
3881 CallArgs.push_back(UBParam);
3882 CallArgs.push_back(StParam);
3883 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003884 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003885 }
3886 CallArgs.push_back(SharedsParam);
3887
Alexey Bataev3c595a62017-08-14 15:01:03 +00003888 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3889 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003890 CGF.EmitStoreThroughLValue(
3891 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003892 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003893 CGF.FinishFunction();
3894 return TaskEntry;
3895}
3896
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003897static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3898 SourceLocation Loc,
3899 QualType KmpInt32Ty,
3900 QualType KmpTaskTWithPrivatesPtrQTy,
3901 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003902 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003903 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003904 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3905 ImplicitParamDecl::Other);
3906 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3907 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3908 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003909 Args.push_back(&GtidArg);
3910 Args.push_back(&TaskTypeArg);
3911 FunctionType::ExtInfo Info;
3912 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003913 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003914 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3915 auto *DestructorFn =
3916 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3917 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003918 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3919 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003920 CodeGenFunction CGF(CGM);
3921 CGF.disableDebugInfo();
3922 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3923 Args);
3924
Alexey Bataev31300ed2016-02-04 11:27:03 +00003925 LValue Base = CGF.EmitLoadOfPointerLValue(
3926 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3927 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003928 auto *KmpTaskTWithPrivatesQTyRD =
3929 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3930 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003931 Base = CGF.EmitLValueForField(Base, *FI);
3932 for (auto *Field :
3933 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3934 if (auto DtorKind = Field->getType().isDestructedType()) {
3935 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3936 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3937 }
3938 }
3939 CGF.FinishFunction();
3940 return DestructorFn;
3941}
3942
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003943/// \brief Emit a privates mapping function for correct handling of private and
3944/// firstprivate variables.
3945/// \code
3946/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3947/// **noalias priv1,..., <tyn> **noalias privn) {
3948/// *priv1 = &.privates.priv1;
3949/// ...;
3950/// *privn = &.privates.privn;
3951/// }
3952/// \endcode
3953static llvm::Value *
3954emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003955 ArrayRef<const Expr *> PrivateVars,
3956 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003957 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003958 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003959 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003960 auto &C = CGM.getContext();
3961 FunctionArgList Args;
3962 ImplicitParamDecl TaskPrivatesArg(
3963 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003964 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3965 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003966 Args.push_back(&TaskPrivatesArg);
3967 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3968 unsigned Counter = 1;
3969 for (auto *E: PrivateVars) {
3970 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003971 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3972 C.getPointerType(C.getPointerType(E->getType()))
3973 .withConst()
3974 .withRestrict(),
3975 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003976 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3977 PrivateVarsPos[VD] = Counter;
3978 ++Counter;
3979 }
3980 for (auto *E : FirstprivateVars) {
3981 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003982 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3983 C.getPointerType(C.getPointerType(E->getType()))
3984 .withConst()
3985 .withRestrict(),
3986 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003987 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3988 PrivateVarsPos[VD] = Counter;
3989 ++Counter;
3990 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003991 for (auto *E: LastprivateVars) {
3992 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003993 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3994 C.getPointerType(C.getPointerType(E->getType()))
3995 .withConst()
3996 .withRestrict(),
3997 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003998 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3999 PrivateVarsPos[VD] = Counter;
4000 ++Counter;
4001 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004002 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004003 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004004 auto *TaskPrivatesMapTy =
4005 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4006 auto *TaskPrivatesMap = llvm::Function::Create(
4007 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4008 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004009 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4010 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004011 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004012 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004013 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004014 CodeGenFunction CGF(CGM);
4015 CGF.disableDebugInfo();
4016 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4017 TaskPrivatesMapFnInfo, Args);
4018
4019 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004020 LValue Base = CGF.EmitLoadOfPointerLValue(
4021 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4022 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004023 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4024 Counter = 0;
4025 for (auto *Field : PrivatesQTyRD->fields()) {
4026 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4027 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004028 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004029 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4030 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004031 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004032 ++Counter;
4033 }
4034 CGF.FinishFunction();
4035 return TaskPrivatesMap;
4036}
4037
Alexey Bataev9e034042015-05-05 04:05:12 +00004038static int array_pod_sort_comparator(const PrivateDataTy *P1,
4039 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004040 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4041}
4042
Alexey Bataevf93095a2016-05-05 08:46:22 +00004043/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004044static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004045 const OMPExecutableDirective &D,
4046 Address KmpTaskSharedsPtr, LValue TDBase,
4047 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4048 QualType SharedsTy, QualType SharedsPtrTy,
4049 const OMPTaskDataTy &Data,
4050 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4051 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004052 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4053 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4054 LValue SrcBase;
4055 if (!Data.FirstprivateVars.empty()) {
4056 SrcBase = CGF.MakeAddrLValue(
4057 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4058 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4059 SharedsTy);
4060 }
4061 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4062 cast<CapturedStmt>(*D.getAssociatedStmt()));
4063 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4064 for (auto &&Pair : Privates) {
4065 auto *VD = Pair.second.PrivateCopy;
4066 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004067 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4068 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004069 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004070 if (auto *Elem = Pair.second.PrivateElemInit) {
4071 auto *OriginalVD = Pair.second.Original;
4072 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4073 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4074 SharedRefLValue = CGF.MakeAddrLValue(
4075 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004076 SharedRefLValue.getType(),
4077 LValueBaseInfo(AlignmentSource::Decl,
4078 SharedRefLValue.getBaseInfo().getMayAlias()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004079 QualType Type = OriginalVD->getType();
4080 if (Type->isArrayType()) {
4081 // Initialize firstprivate array.
4082 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4083 // Perform simple memcpy.
4084 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4085 SharedRefLValue.getAddress(), Type);
4086 } else {
4087 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004088 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004089 CGF.EmitOMPAggregateAssign(
4090 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4091 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4092 Address SrcElement) {
4093 // Clean up any temporaries needed by the initialization.
4094 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4095 InitScope.addPrivate(
4096 Elem, [SrcElement]() -> Address { return SrcElement; });
4097 (void)InitScope.Privatize();
4098 // Emit initialization for single element.
4099 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4100 CGF, &CapturesInfo);
4101 CGF.EmitAnyExprToMem(Init, DestElement,
4102 Init->getType().getQualifiers(),
4103 /*IsInitializer=*/false);
4104 });
4105 }
4106 } else {
4107 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4108 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4109 return SharedRefLValue.getAddress();
4110 });
4111 (void)InitScope.Privatize();
4112 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4113 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4114 /*capturedByInit=*/false);
4115 }
4116 } else
4117 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4118 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004119 ++FI;
4120 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004121}
4122
4123/// Check if duplication function is required for taskloops.
4124static bool checkInitIsRequired(CodeGenFunction &CGF,
4125 ArrayRef<PrivateDataTy> Privates) {
4126 bool InitRequired = false;
4127 for (auto &&Pair : Privates) {
4128 auto *VD = Pair.second.PrivateCopy;
4129 auto *Init = VD->getAnyInitializer();
4130 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4131 !CGF.isTrivialInitializer(Init));
4132 }
4133 return InitRequired;
4134}
4135
4136
4137/// Emit task_dup function (for initialization of
4138/// private/firstprivate/lastprivate vars and last_iter flag)
4139/// \code
4140/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4141/// lastpriv) {
4142/// // setup lastprivate flag
4143/// task_dst->last = lastpriv;
4144/// // could be constructor calls here...
4145/// }
4146/// \endcode
4147static llvm::Value *
4148emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4149 const OMPExecutableDirective &D,
4150 QualType KmpTaskTWithPrivatesPtrQTy,
4151 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4152 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4153 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4154 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4155 auto &C = CGM.getContext();
4156 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004157 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4158 KmpTaskTWithPrivatesPtrQTy,
4159 ImplicitParamDecl::Other);
4160 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4161 KmpTaskTWithPrivatesPtrQTy,
4162 ImplicitParamDecl::Other);
4163 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4164 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004165 Args.push_back(&DstArg);
4166 Args.push_back(&SrcArg);
4167 Args.push_back(&LastprivArg);
4168 auto &TaskDupFnInfo =
4169 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4170 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4171 auto *TaskDup =
4172 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4173 ".omp_task_dup.", &CGM.getModule());
4174 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4175 CodeGenFunction CGF(CGM);
4176 CGF.disableDebugInfo();
4177 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4178
4179 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4180 CGF.GetAddrOfLocalVar(&DstArg),
4181 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4182 // task_dst->liter = lastpriv;
4183 if (WithLastIter) {
4184 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4185 LValue Base = CGF.EmitLValueForField(
4186 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4187 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4188 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4189 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4190 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4191 }
4192
4193 // Emit initial values for private copies (if any).
4194 assert(!Privates.empty());
4195 Address KmpTaskSharedsPtr = Address::invalid();
4196 if (!Data.FirstprivateVars.empty()) {
4197 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4198 CGF.GetAddrOfLocalVar(&SrcArg),
4199 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4200 LValue Base = CGF.EmitLValueForField(
4201 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4202 KmpTaskSharedsPtr = Address(
4203 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4204 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4205 KmpTaskTShareds)),
4206 Loc),
4207 CGF.getNaturalTypeAlignment(SharedsTy));
4208 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004209 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4210 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004211 CGF.FinishFunction();
4212 return TaskDup;
4213}
4214
Alexey Bataev8a831592016-05-10 10:36:51 +00004215/// Checks if destructor function is required to be generated.
4216/// \return true if cleanups are required, false otherwise.
4217static bool
4218checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4219 bool NeedsCleanup = false;
4220 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4221 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4222 for (auto *FD : PrivateRD->fields()) {
4223 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4224 if (NeedsCleanup)
4225 break;
4226 }
4227 return NeedsCleanup;
4228}
4229
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004230CGOpenMPRuntime::TaskResultTy
4231CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4232 const OMPExecutableDirective &D,
4233 llvm::Value *TaskFunction, QualType SharedsTy,
4234 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004235 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004236 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004237 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004238 auto I = Data.PrivateCopies.begin();
4239 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +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(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4244 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004245 ++I;
4246 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004247 I = Data.FirstprivateCopies.begin();
4248 auto IElemInitRef = Data.FirstprivateInits.begin();
4249 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004250 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4251 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004252 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004253 PrivateHelpersTy(
4254 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4255 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004256 ++I;
4257 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004258 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004259 I = Data.LastprivateCopies.begin();
4260 for (auto *E : Data.LastprivateVars) {
4261 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4262 Privates.push_back(std::make_pair(
4263 C.getDeclAlign(VD),
4264 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4265 /*PrivateElemInit=*/nullptr)));
4266 ++I;
4267 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004268 llvm::array_pod_sort(Privates.begin(), Privates.end(),
4269 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004270 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4271 // Build type kmp_routine_entry_t (if not built yet).
4272 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004273 // Build type kmp_task_t (if not built yet).
4274 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004275 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4276 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004277 }
4278 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004279 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004280 auto *KmpTaskTWithPrivatesQTyRD =
4281 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4282 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4283 QualType KmpTaskTWithPrivatesPtrQTy =
4284 C.getPointerType(KmpTaskTWithPrivatesQTy);
4285 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4286 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004287 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004288 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4289
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004290 // Emit initial values for private copies (if any).
4291 llvm::Value *TaskPrivatesMap = nullptr;
4292 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004293 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004294 if (!Privates.empty()) {
4295 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004296 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4297 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4298 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004299 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4300 TaskPrivatesMap, TaskPrivatesMapTy);
4301 } else {
4302 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4303 cast<llvm::PointerType>(TaskPrivatesMapTy));
4304 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004305 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4306 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004307 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004308 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4309 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4310 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004311
4312 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4313 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4314 // kmp_routine_entry_t *task_entry);
4315 // Task flags. Format is taken from
4316 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4317 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004318 enum {
4319 TiedFlag = 0x1,
4320 FinalFlag = 0x2,
4321 DestructorsFlag = 0x8,
4322 PriorityFlag = 0x20
4323 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004324 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004325 bool NeedsCleanup = false;
4326 if (!Privates.empty()) {
4327 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4328 if (NeedsCleanup)
4329 Flags = Flags | DestructorsFlag;
4330 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004331 if (Data.Priority.getInt())
4332 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004333 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004334 Data.Final.getPointer()
4335 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004336 CGF.Builder.getInt32(FinalFlag),
4337 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004338 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004339 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004340 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004341 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4342 getThreadID(CGF, Loc), TaskFlags,
4343 KmpTaskTWithPrivatesTySize, SharedsSize,
4344 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4345 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004346 auto *NewTask = CGF.EmitRuntimeCall(
4347 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004348 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4349 NewTask, KmpTaskTWithPrivatesPtrTy);
4350 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4351 KmpTaskTWithPrivatesQTy);
4352 LValue TDBase =
4353 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004354 // Fill the data in the resulting kmp_task_t record.
4355 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004356 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004357 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004358 KmpTaskSharedsPtr =
4359 Address(CGF.EmitLoadOfScalar(
4360 CGF.EmitLValueForField(
4361 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4362 KmpTaskTShareds)),
4363 Loc),
4364 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004365 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004366 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004367 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004368 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004369 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004370 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4371 SharedsTy, SharedsPtrTy, Data, Privates,
4372 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004373 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4374 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4375 Result.TaskDupFn = emitTaskDupFunction(
4376 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4377 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4378 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004379 }
4380 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004381 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4382 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004383 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004384 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4385 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4386 if (NeedsCleanup) {
4387 llvm::Value *DestructorFn = emitDestructorsFunction(
4388 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4389 KmpTaskTWithPrivatesQTy);
4390 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4391 LValue DestructorsLV = CGF.EmitLValueForField(
4392 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4393 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4394 DestructorFn, KmpRoutineEntryPtrTy),
4395 DestructorsLV);
4396 }
4397 // Set priority.
4398 if (Data.Priority.getInt()) {
4399 LValue Data2LV = CGF.EmitLValueForField(
4400 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4401 LValue PriorityLV = CGF.EmitLValueForField(
4402 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4403 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4404 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004405 Result.NewTask = NewTask;
4406 Result.TaskEntry = TaskEntry;
4407 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4408 Result.TDBase = TDBase;
4409 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4410 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004411}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004412
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004413void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4414 const OMPExecutableDirective &D,
4415 llvm::Value *TaskFunction,
4416 QualType SharedsTy, Address Shareds,
4417 const Expr *IfCond,
4418 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004419 if (!CGF.HaveInsertPoint())
4420 return;
4421
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004422 TaskResultTy Result =
4423 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4424 llvm::Value *NewTask = Result.NewTask;
4425 llvm::Value *TaskEntry = Result.TaskEntry;
4426 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4427 LValue TDBase = Result.TDBase;
4428 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004429 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004430 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004431 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004432 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004433 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004434 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004435 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004436 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4437 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004438 QualType FlagsTy =
4439 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004440 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4441 if (KmpDependInfoTy.isNull()) {
4442 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4443 KmpDependInfoRD->startDefinition();
4444 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4445 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4446 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4447 KmpDependInfoRD->completeDefinition();
4448 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004449 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004450 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004451 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004452 // Define type kmp_depend_info[<Dependences.size()>];
4453 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004454 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004455 ArrayType::Normal, /*IndexTypeQuals=*/0);
4456 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004457 DependenciesArray =
4458 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004459 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004460 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004461 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004462 llvm::Value *Size;
4463 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004464 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4465 LValue UpAddrLVal =
4466 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4467 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004468 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004469 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004470 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004471 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4472 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004473 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004474 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004475 auto Base = CGF.MakeAddrLValue(
4476 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004477 KmpDependInfoTy);
4478 // deps[i].base_addr = &<Dependences[i].second>;
4479 auto BaseAddrLVal = CGF.EmitLValueForField(
4480 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004481 CGF.EmitStoreOfScalar(
4482 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4483 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004484 // deps[i].len = sizeof(<Dependences[i].second>);
4485 auto LenLVal = CGF.EmitLValueForField(
4486 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4487 CGF.EmitStoreOfScalar(Size, LenLVal);
4488 // deps[i].flags = <Dependences[i].first>;
4489 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004490 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004491 case OMPC_DEPEND_in:
4492 DepKind = DepIn;
4493 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004494 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004495 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004496 case OMPC_DEPEND_inout:
4497 DepKind = DepInOut;
4498 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004499 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004500 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004501 case OMPC_DEPEND_unknown:
4502 llvm_unreachable("Unknown task dependence type");
4503 }
4504 auto FlagsLVal = CGF.EmitLValueForField(
4505 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4506 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4507 FlagsLVal);
4508 }
John McCall7f416cc2015-09-08 08:05:57 +00004509 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4510 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004511 CGF.VoidPtrTy);
4512 }
4513
Alexey Bataev62b63b12015-03-10 07:28:44 +00004514 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4515 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004516 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4517 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4518 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4519 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004520 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004521 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004522 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4523 llvm::Value *DepTaskArgs[7];
4524 if (NumDependencies) {
4525 DepTaskArgs[0] = UpLoc;
4526 DepTaskArgs[1] = ThreadID;
4527 DepTaskArgs[2] = NewTask;
4528 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4529 DepTaskArgs[4] = DependenciesArray.getPointer();
4530 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4531 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4532 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004533 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4534 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004535 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004536 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004537 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4538 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4539 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4540 }
John McCall7f416cc2015-09-08 08:05:57 +00004541 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004542 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004543 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004544 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004545 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004546 TaskArgs);
4547 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004548 // Check if parent region is untied and build return for untied task;
4549 if (auto *Region =
4550 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4551 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004552 };
John McCall7f416cc2015-09-08 08:05:57 +00004553
4554 llvm::Value *DepWaitTaskArgs[6];
4555 if (NumDependencies) {
4556 DepWaitTaskArgs[0] = UpLoc;
4557 DepWaitTaskArgs[1] = ThreadID;
4558 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4559 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4560 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4561 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4562 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004563 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004564 NumDependencies, &DepWaitTaskArgs,
4565 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004566 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004567 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4568 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4569 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4570 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4571 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004572 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004573 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004574 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004575 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004576 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4577 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004578 Action.Enter(CGF);
4579 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004580 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004581 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004582 };
4583
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004584 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4585 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004586 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4587 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004588 RegionCodeGenTy RCG(CodeGen);
4589 CommonActionTy Action(
4590 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4591 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4592 RCG.setAction(Action);
4593 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004594 };
John McCall7f416cc2015-09-08 08:05:57 +00004595
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004596 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004597 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004598 else {
4599 RegionCodeGenTy ThenRCG(ThenCodeGen);
4600 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004601 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004602}
4603
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004604void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4605 const OMPLoopDirective &D,
4606 llvm::Value *TaskFunction,
4607 QualType SharedsTy, Address Shareds,
4608 const Expr *IfCond,
4609 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004610 if (!CGF.HaveInsertPoint())
4611 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004612 TaskResultTy Result =
4613 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004614 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4615 // libcall.
4616 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4617 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4618 // sched, kmp_uint64 grainsize, void *task_dup);
4619 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4620 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4621 llvm::Value *IfVal;
4622 if (IfCond) {
4623 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4624 /*isSigned=*/true);
4625 } else
4626 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4627
4628 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004629 Result.TDBase,
4630 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004631 auto *LBVar =
4632 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4633 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4634 /*IsInitializer=*/true);
4635 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004636 Result.TDBase,
4637 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004638 auto *UBVar =
4639 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4640 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4641 /*IsInitializer=*/true);
4642 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004643 Result.TDBase,
4644 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004645 auto *StVar =
4646 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4647 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4648 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004649 // Store reductions address.
4650 LValue RedLVal = CGF.EmitLValueForField(
4651 Result.TDBase,
4652 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4653 if (Data.Reductions)
4654 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4655 else {
4656 CGF.EmitNullInitialization(RedLVal.getAddress(),
4657 CGF.getContext().VoidPtrTy);
4658 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004659 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004660 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004661 UpLoc,
4662 ThreadID,
4663 Result.NewTask,
4664 IfVal,
4665 LBLVal.getPointer(),
4666 UBLVal.getPointer(),
4667 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4668 llvm::ConstantInt::getNullValue(
4669 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004670 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004671 CGF.IntTy, Data.Schedule.getPointer()
4672 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004673 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004674 Data.Schedule.getPointer()
4675 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004676 /*isSigned=*/false)
4677 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004678 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4679 Result.TaskDupFn, CGF.VoidPtrTy)
4680 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004681 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4682}
4683
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004684/// \brief Emit reduction operation for each element of array (required for
4685/// array sections) LHS op = RHS.
4686/// \param Type Type of array.
4687/// \param LHSVar Variable on the left side of the reduction operation
4688/// (references element of array in original variable).
4689/// \param RHSVar Variable on the right side of the reduction operation
4690/// (references element of array in original variable).
4691/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4692/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004693static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004694 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4695 const VarDecl *RHSVar,
4696 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4697 const Expr *, const Expr *)> &RedOpGen,
4698 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4699 const Expr *UpExpr = nullptr) {
4700 // Perform element-by-element initialization.
4701 QualType ElementTy;
4702 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4703 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4704
4705 // Drill down to the base element type on both arrays.
4706 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4707 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4708
4709 auto RHSBegin = RHSAddr.getPointer();
4710 auto LHSBegin = LHSAddr.getPointer();
4711 // Cast from pointer to array type to pointer to single element.
4712 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4713 // The basic structure here is a while-do loop.
4714 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4715 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4716 auto IsEmpty =
4717 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4718 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4719
4720 // Enter the loop body, making that address the current address.
4721 auto EntryBB = CGF.Builder.GetInsertBlock();
4722 CGF.EmitBlock(BodyBB);
4723
4724 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4725
4726 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4727 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4728 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4729 Address RHSElementCurrent =
4730 Address(RHSElementPHI,
4731 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4732
4733 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4734 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4735 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4736 Address LHSElementCurrent =
4737 Address(LHSElementPHI,
4738 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4739
4740 // Emit copy.
4741 CodeGenFunction::OMPPrivateScope Scope(CGF);
4742 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4743 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4744 Scope.Privatize();
4745 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4746 Scope.ForceCleanup();
4747
4748 // Shift the address forward by one element.
4749 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4750 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4751 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4752 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4753 // Check whether we've reached the end.
4754 auto Done =
4755 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4756 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4757 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4758 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4759
4760 // Done.
4761 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4762}
4763
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004764/// Emit reduction combiner. If the combiner is a simple expression emit it as
4765/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4766/// UDR combiner function.
4767static void emitReductionCombiner(CodeGenFunction &CGF,
4768 const Expr *ReductionOp) {
4769 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4770 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4771 if (auto *DRE =
4772 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4773 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4774 std::pair<llvm::Function *, llvm::Function *> Reduction =
4775 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4776 RValue Func = RValue::get(Reduction.first);
4777 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4778 CGF.EmitIgnoredExpr(ReductionOp);
4779 return;
4780 }
4781 CGF.EmitIgnoredExpr(ReductionOp);
4782}
4783
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004784llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4785 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4786 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4787 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004788 auto &C = CGM.getContext();
4789
4790 // void reduction_func(void *LHSArg, void *RHSArg);
4791 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004792 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4793 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004794 Args.push_back(&LHSArg);
4795 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004796 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004797 auto *Fn = llvm::Function::Create(
4798 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4799 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004800 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004801 CodeGenFunction CGF(CGM);
4802 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4803
4804 // Dst = (void*[n])(LHSArg);
4805 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004806 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4807 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4808 ArgsType), CGF.getPointerAlign());
4809 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4810 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4811 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004812
4813 // ...
4814 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4815 // ...
4816 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004817 auto IPriv = Privates.begin();
4818 unsigned Idx = 0;
4819 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004820 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4821 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004822 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004823 });
4824 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4825 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004826 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004827 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004828 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004829 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004830 // Get array size and emit VLA type.
4831 ++Idx;
4832 Address Elem =
4833 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4834 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004835 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4836 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004837 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004838 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004839 CGF.EmitVariablyModifiedType(PrivTy);
4840 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004841 }
4842 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004843 IPriv = Privates.begin();
4844 auto ILHS = LHSExprs.begin();
4845 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004846 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004847 if ((*IPriv)->getType()->isArrayType()) {
4848 // Emit reduction for array section.
4849 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4850 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004851 EmitOMPAggregateReduction(
4852 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4853 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4854 emitReductionCombiner(CGF, E);
4855 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004856 } else
4857 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004858 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004859 ++IPriv;
4860 ++ILHS;
4861 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004862 }
4863 Scope.ForceCleanup();
4864 CGF.FinishFunction();
4865 return Fn;
4866}
4867
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004868void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4869 const Expr *ReductionOp,
4870 const Expr *PrivateRef,
4871 const DeclRefExpr *LHS,
4872 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004873 if (PrivateRef->getType()->isArrayType()) {
4874 // Emit reduction for array section.
4875 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4876 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4877 EmitOMPAggregateReduction(
4878 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4879 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4880 emitReductionCombiner(CGF, ReductionOp);
4881 });
4882 } else
4883 // Emit reduction for array subscript or single variable.
4884 emitReductionCombiner(CGF, ReductionOp);
4885}
4886
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004887void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004888 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004889 ArrayRef<const Expr *> LHSExprs,
4890 ArrayRef<const Expr *> RHSExprs,
4891 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004892 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004893 if (!CGF.HaveInsertPoint())
4894 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004895
4896 bool WithNowait = Options.WithNowait;
4897 bool SimpleReduction = Options.SimpleReduction;
4898
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004899 // Next code should be emitted for reduction:
4900 //
4901 // static kmp_critical_name lock = { 0 };
4902 //
4903 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4904 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4905 // ...
4906 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4907 // *(Type<n>-1*)rhs[<n>-1]);
4908 // }
4909 //
4910 // ...
4911 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4912 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4913 // RedList, reduce_func, &<lock>)) {
4914 // case 1:
4915 // ...
4916 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4917 // ...
4918 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4919 // break;
4920 // case 2:
4921 // ...
4922 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4923 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004924 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004925 // break;
4926 // default:;
4927 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004928 //
4929 // if SimpleReduction is true, only the next code is generated:
4930 // ...
4931 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4932 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004933
4934 auto &C = CGM.getContext();
4935
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004936 if (SimpleReduction) {
4937 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004938 auto IPriv = Privates.begin();
4939 auto ILHS = LHSExprs.begin();
4940 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004941 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004942 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4943 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004944 ++IPriv;
4945 ++ILHS;
4946 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004947 }
4948 return;
4949 }
4950
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004951 // 1. Build a list of reduction variables.
4952 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004953 auto Size = RHSExprs.size();
4954 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004955 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004956 // Reserve place for array size.
4957 ++Size;
4958 }
4959 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004960 QualType ReductionArrayTy =
4961 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4962 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004963 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004964 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004965 auto IPriv = Privates.begin();
4966 unsigned Idx = 0;
4967 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004968 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004969 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004970 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004971 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004972 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4973 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004974 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004975 // Store array size.
4976 ++Idx;
4977 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4978 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004979 llvm::Value *Size = CGF.Builder.CreateIntCast(
4980 CGF.getVLASize(
4981 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4982 .first,
4983 CGF.SizeTy, /*isSigned=*/false);
4984 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4985 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004986 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004987 }
4988
4989 // 2. Emit reduce_func().
4990 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004991 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4992 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004993
4994 // 3. Create static kmp_critical_name lock = { 0 };
4995 auto *Lock = getCriticalRegionLock(".reduction");
4996
4997 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4998 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004999 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005000 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005001 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005002 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5003 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005004 llvm::Value *Args[] = {
5005 IdentTLoc, // ident_t *<loc>
5006 ThreadId, // i32 <gtid>
5007 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5008 ReductionArrayTySize, // size_type sizeof(RedList)
5009 RL, // void *RedList
5010 ReductionFn, // void (*) (void *, void *) <reduce_func>
5011 Lock // kmp_critical_name *&<lock>
5012 };
5013 auto Res = CGF.EmitRuntimeCall(
5014 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5015 : OMPRTL__kmpc_reduce),
5016 Args);
5017
5018 // 5. Build switch(res)
5019 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5020 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5021
5022 // 6. Build case 1:
5023 // ...
5024 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5025 // ...
5026 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5027 // break;
5028 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5029 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5030 CGF.EmitBlock(Case1BB);
5031
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005032 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5033 llvm::Value *EndArgs[] = {
5034 IdentTLoc, // ident_t *<loc>
5035 ThreadId, // i32 <gtid>
5036 Lock // kmp_critical_name *&<lock>
5037 };
5038 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5039 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005040 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005041 auto IPriv = Privates.begin();
5042 auto ILHS = LHSExprs.begin();
5043 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005044 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005045 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5046 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005047 ++IPriv;
5048 ++ILHS;
5049 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005050 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005051 };
5052 RegionCodeGenTy RCG(CodeGen);
5053 CommonActionTy Action(
5054 nullptr, llvm::None,
5055 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5056 : OMPRTL__kmpc_end_reduce),
5057 EndArgs);
5058 RCG.setAction(Action);
5059 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005060
5061 CGF.EmitBranch(DefaultBB);
5062
5063 // 7. Build case 2:
5064 // ...
5065 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5066 // ...
5067 // break;
5068 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5069 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5070 CGF.EmitBlock(Case2BB);
5071
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005072 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5073 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005074 auto ILHS = LHSExprs.begin();
5075 auto IRHS = RHSExprs.begin();
5076 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005077 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005078 const Expr *XExpr = nullptr;
5079 const Expr *EExpr = nullptr;
5080 const Expr *UpExpr = nullptr;
5081 BinaryOperatorKind BO = BO_Comma;
5082 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5083 if (BO->getOpcode() == BO_Assign) {
5084 XExpr = BO->getLHS();
5085 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005086 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005087 }
5088 // Try to emit update expression as a simple atomic.
5089 auto *RHSExpr = UpExpr;
5090 if (RHSExpr) {
5091 // Analyze RHS part of the whole expression.
5092 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5093 RHSExpr->IgnoreParenImpCasts())) {
5094 // If this is a conditional operator, analyze its condition for
5095 // min/max reduction operator.
5096 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005097 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005098 if (auto *BORHS =
5099 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5100 EExpr = BORHS->getRHS();
5101 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005102 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005103 }
5104 if (XExpr) {
5105 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005106 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005107 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5108 const Expr *EExpr, const Expr *UpExpr) {
5109 LValue X = CGF.EmitLValue(XExpr);
5110 RValue E;
5111 if (EExpr)
5112 E = CGF.EmitAnyExpr(EExpr);
5113 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005114 X, E, BO, /*IsXLHSInRHSPart=*/true,
5115 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005116 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005117 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5118 PrivateScope.addPrivate(
5119 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5120 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5121 CGF.emitOMPSimpleStore(
5122 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5123 VD->getType().getNonReferenceType(), Loc);
5124 return LHSTemp;
5125 });
5126 (void)PrivateScope.Privatize();
5127 return CGF.EmitAnyExpr(UpExpr);
5128 });
5129 };
5130 if ((*IPriv)->getType()->isArrayType()) {
5131 // Emit atomic reduction for array section.
5132 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5133 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5134 AtomicRedGen, XExpr, EExpr, UpExpr);
5135 } else
5136 // Emit atomic reduction for array subscript or single variable.
5137 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5138 } else {
5139 // Emit as a critical region.
5140 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5141 const Expr *, const Expr *) {
5142 auto &RT = CGF.CGM.getOpenMPRuntime();
5143 RT.emitCriticalRegion(
5144 CGF, ".atomic_reduction",
5145 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5146 Action.Enter(CGF);
5147 emitReductionCombiner(CGF, E);
5148 },
5149 Loc);
5150 };
5151 if ((*IPriv)->getType()->isArrayType()) {
5152 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5153 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5154 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5155 CritRedGen);
5156 } else
5157 CritRedGen(CGF, nullptr, nullptr, nullptr);
5158 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005159 ++ILHS;
5160 ++IRHS;
5161 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005162 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005163 };
5164 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5165 if (!WithNowait) {
5166 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5167 llvm::Value *EndArgs[] = {
5168 IdentTLoc, // ident_t *<loc>
5169 ThreadId, // i32 <gtid>
5170 Lock // kmp_critical_name *&<lock>
5171 };
5172 CommonActionTy Action(nullptr, llvm::None,
5173 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5174 EndArgs);
5175 AtomicRCG.setAction(Action);
5176 AtomicRCG(CGF);
5177 } else
5178 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005179
5180 CGF.EmitBranch(DefaultBB);
5181 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5182}
5183
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005184/// Generates unique name for artificial threadprivate variables.
5185/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5186static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5187 unsigned N) {
5188 SmallString<256> Buffer;
5189 llvm::raw_svector_ostream Out(Buffer);
5190 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5191 return Out.str();
5192}
5193
5194/// Emits reduction initializer function:
5195/// \code
5196/// void @.red_init(void* %arg) {
5197/// %0 = bitcast void* %arg to <type>*
5198/// store <type> <init>, <type>* %0
5199/// ret void
5200/// }
5201/// \endcode
5202static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5203 SourceLocation Loc,
5204 ReductionCodeGen &RCG, unsigned N) {
5205 auto &C = CGM.getContext();
5206 FunctionArgList Args;
5207 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5208 Args.emplace_back(&Param);
5209 auto &FnInfo =
5210 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5211 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5212 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5213 ".red_init.", &CGM.getModule());
5214 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5215 CodeGenFunction CGF(CGM);
5216 CGF.disableDebugInfo();
5217 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5218 Address PrivateAddr = CGF.EmitLoadOfPointer(
5219 CGF.GetAddrOfLocalVar(&Param),
5220 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5221 llvm::Value *Size = nullptr;
5222 // If the size of the reduction item is non-constant, load it from global
5223 // threadprivate variable.
5224 if (RCG.getSizes(N).second) {
5225 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5226 CGF, CGM.getContext().getSizeType(),
5227 generateUniqueName("reduction_size", Loc, N));
5228 Size =
5229 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5230 CGM.getContext().getSizeType(), SourceLocation());
5231 }
5232 RCG.emitAggregateType(CGF, N, Size);
5233 LValue SharedLVal;
5234 // If initializer uses initializer from declare reduction construct, emit a
5235 // pointer to the address of the original reduction item (reuired by reduction
5236 // initializer)
5237 if (RCG.usesReductionInitializer(N)) {
5238 Address SharedAddr =
5239 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5240 CGF, CGM.getContext().VoidPtrTy,
5241 generateUniqueName("reduction", Loc, N));
5242 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5243 } else {
5244 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5245 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5246 CGM.getContext().VoidPtrTy);
5247 }
5248 // Emit the initializer:
5249 // %0 = bitcast void* %arg to <type>*
5250 // store <type> <init>, <type>* %0
5251 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5252 [](CodeGenFunction &) { return false; });
5253 CGF.FinishFunction();
5254 return Fn;
5255}
5256
5257/// Emits reduction combiner function:
5258/// \code
5259/// void @.red_comb(void* %arg0, void* %arg1) {
5260/// %lhs = bitcast void* %arg0 to <type>*
5261/// %rhs = bitcast void* %arg1 to <type>*
5262/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5263/// store <type> %2, <type>* %lhs
5264/// ret void
5265/// }
5266/// \endcode
5267static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5268 SourceLocation Loc,
5269 ReductionCodeGen &RCG, unsigned N,
5270 const Expr *ReductionOp,
5271 const Expr *LHS, const Expr *RHS,
5272 const Expr *PrivateRef) {
5273 auto &C = CGM.getContext();
5274 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5275 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5276 FunctionArgList Args;
5277 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5278 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5279 Args.emplace_back(&ParamInOut);
5280 Args.emplace_back(&ParamIn);
5281 auto &FnInfo =
5282 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5283 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5284 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5285 ".red_comb.", &CGM.getModule());
5286 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5287 CodeGenFunction CGF(CGM);
5288 CGF.disableDebugInfo();
5289 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5290 llvm::Value *Size = nullptr;
5291 // If the size of the reduction item is non-constant, load it from global
5292 // threadprivate variable.
5293 if (RCG.getSizes(N).second) {
5294 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5295 CGF, CGM.getContext().getSizeType(),
5296 generateUniqueName("reduction_size", Loc, N));
5297 Size =
5298 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5299 CGM.getContext().getSizeType(), SourceLocation());
5300 }
5301 RCG.emitAggregateType(CGF, N, Size);
5302 // Remap lhs and rhs variables to the addresses of the function arguments.
5303 // %lhs = bitcast void* %arg0 to <type>*
5304 // %rhs = bitcast void* %arg1 to <type>*
5305 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5306 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5307 // Pull out the pointer to the variable.
5308 Address PtrAddr = CGF.EmitLoadOfPointer(
5309 CGF.GetAddrOfLocalVar(&ParamInOut),
5310 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5311 return CGF.Builder.CreateElementBitCast(
5312 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5313 });
5314 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5315 // Pull out the pointer to the variable.
5316 Address PtrAddr = CGF.EmitLoadOfPointer(
5317 CGF.GetAddrOfLocalVar(&ParamIn),
5318 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5319 return CGF.Builder.CreateElementBitCast(
5320 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5321 });
5322 PrivateScope.Privatize();
5323 // Emit the combiner body:
5324 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5325 // store <type> %2, <type>* %lhs
5326 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5327 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5328 cast<DeclRefExpr>(RHS));
5329 CGF.FinishFunction();
5330 return Fn;
5331}
5332
5333/// Emits reduction finalizer function:
5334/// \code
5335/// void @.red_fini(void* %arg) {
5336/// %0 = bitcast void* %arg to <type>*
5337/// <destroy>(<type>* %0)
5338/// ret void
5339/// }
5340/// \endcode
5341static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5342 SourceLocation Loc,
5343 ReductionCodeGen &RCG, unsigned N) {
5344 if (!RCG.needCleanups(N))
5345 return nullptr;
5346 auto &C = CGM.getContext();
5347 FunctionArgList Args;
5348 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5349 Args.emplace_back(&Param);
5350 auto &FnInfo =
5351 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5352 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5353 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5354 ".red_fini.", &CGM.getModule());
5355 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5356 CodeGenFunction CGF(CGM);
5357 CGF.disableDebugInfo();
5358 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5359 Address PrivateAddr = CGF.EmitLoadOfPointer(
5360 CGF.GetAddrOfLocalVar(&Param),
5361 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5362 llvm::Value *Size = nullptr;
5363 // If the size of the reduction item is non-constant, load it from global
5364 // threadprivate variable.
5365 if (RCG.getSizes(N).second) {
5366 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5367 CGF, CGM.getContext().getSizeType(),
5368 generateUniqueName("reduction_size", Loc, N));
5369 Size =
5370 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5371 CGM.getContext().getSizeType(), SourceLocation());
5372 }
5373 RCG.emitAggregateType(CGF, N, Size);
5374 // Emit the finalizer body:
5375 // <destroy>(<type>* %0)
5376 RCG.emitCleanups(CGF, N, PrivateAddr);
5377 CGF.FinishFunction();
5378 return Fn;
5379}
5380
5381llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5382 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5383 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5384 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5385 return nullptr;
5386
5387 // Build typedef struct:
5388 // kmp_task_red_input {
5389 // void *reduce_shar; // shared reduction item
5390 // size_t reduce_size; // size of data item
5391 // void *reduce_init; // data initialization routine
5392 // void *reduce_fini; // data finalization routine
5393 // void *reduce_comb; // data combiner routine
5394 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5395 // } kmp_task_red_input_t;
5396 ASTContext &C = CGM.getContext();
5397 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5398 RD->startDefinition();
5399 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5400 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5401 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5402 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5403 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5404 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5405 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5406 RD->completeDefinition();
5407 QualType RDType = C.getRecordType(RD);
5408 unsigned Size = Data.ReductionVars.size();
5409 llvm::APInt ArraySize(/*numBits=*/64, Size);
5410 QualType ArrayRDType = C.getConstantArrayType(
5411 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5412 // kmp_task_red_input_t .rd_input.[Size];
5413 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5414 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5415 Data.ReductionOps);
5416 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5417 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5418 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5419 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5420 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5421 TaskRedInput.getPointer(), Idxs,
5422 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5423 ".rd_input.gep.");
5424 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5425 // ElemLVal.reduce_shar = &Shareds[Cnt];
5426 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5427 RCG.emitSharedLValue(CGF, Cnt);
5428 llvm::Value *CastedShared =
5429 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5430 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5431 RCG.emitAggregateType(CGF, Cnt);
5432 llvm::Value *SizeValInChars;
5433 llvm::Value *SizeVal;
5434 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5435 // We use delayed creation/initialization for VLAs, array sections and
5436 // custom reduction initializations. It is required because runtime does not
5437 // provide the way to pass the sizes of VLAs/array sections to
5438 // initializer/combiner/finalizer functions and does not pass the pointer to
5439 // original reduction item to the initializer. Instead threadprivate global
5440 // variables are used to store these values and use them in the functions.
5441 bool DelayedCreation = !!SizeVal;
5442 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5443 /*isSigned=*/false);
5444 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5445 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5446 // ElemLVal.reduce_init = init;
5447 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5448 llvm::Value *InitAddr =
5449 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5450 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5451 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5452 // ElemLVal.reduce_fini = fini;
5453 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5454 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5455 llvm::Value *FiniAddr = Fini
5456 ? CGF.EmitCastToVoidPtr(Fini)
5457 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5458 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5459 // ElemLVal.reduce_comb = comb;
5460 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5461 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5462 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5463 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5464 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5465 // ElemLVal.flags = 0;
5466 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5467 if (DelayedCreation) {
5468 CGF.EmitStoreOfScalar(
5469 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5470 FlagsLVal);
5471 } else
5472 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5473 }
5474 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5475 // *data);
5476 llvm::Value *Args[] = {
5477 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5478 /*isSigned=*/true),
5479 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5480 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5481 CGM.VoidPtrTy)};
5482 return CGF.EmitRuntimeCall(
5483 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5484}
5485
5486void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5487 SourceLocation Loc,
5488 ReductionCodeGen &RCG,
5489 unsigned N) {
5490 auto Sizes = RCG.getSizes(N);
5491 // Emit threadprivate global variable if the type is non-constant
5492 // (Sizes.second = nullptr).
5493 if (Sizes.second) {
5494 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5495 /*isSigned=*/false);
5496 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5497 CGF, CGM.getContext().getSizeType(),
5498 generateUniqueName("reduction_size", Loc, N));
5499 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5500 }
5501 // Store address of the original reduction item if custom initializer is used.
5502 if (RCG.usesReductionInitializer(N)) {
5503 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5504 CGF, CGM.getContext().VoidPtrTy,
5505 generateUniqueName("reduction", Loc, N));
5506 CGF.Builder.CreateStore(
5507 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5508 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5509 SharedAddr, /*IsVolatile=*/false);
5510 }
5511}
5512
5513Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5514 SourceLocation Loc,
5515 llvm::Value *ReductionsPtr,
5516 LValue SharedLVal) {
5517 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5518 // *d);
5519 llvm::Value *Args[] = {
5520 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5521 /*isSigned=*/true),
5522 ReductionsPtr,
5523 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5524 CGM.VoidPtrTy)};
5525 return Address(
5526 CGF.EmitRuntimeCall(
5527 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5528 SharedLVal.getAlignment());
5529}
5530
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005531void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5532 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005533 if (!CGF.HaveInsertPoint())
5534 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005535 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5536 // global_tid);
5537 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5538 // Ignore return result until untied tasks are supported.
5539 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005540 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5541 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005542}
5543
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005544void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005545 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005546 const RegionCodeGenTy &CodeGen,
5547 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005548 if (!CGF.HaveInsertPoint())
5549 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005550 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005551 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005552}
5553
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005554namespace {
5555enum RTCancelKind {
5556 CancelNoreq = 0,
5557 CancelParallel = 1,
5558 CancelLoop = 2,
5559 CancelSections = 3,
5560 CancelTaskgroup = 4
5561};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005562} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005563
5564static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5565 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005566 if (CancelRegion == OMPD_parallel)
5567 CancelKind = CancelParallel;
5568 else if (CancelRegion == OMPD_for)
5569 CancelKind = CancelLoop;
5570 else if (CancelRegion == OMPD_sections)
5571 CancelKind = CancelSections;
5572 else {
5573 assert(CancelRegion == OMPD_taskgroup);
5574 CancelKind = CancelTaskgroup;
5575 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005576 return CancelKind;
5577}
5578
5579void CGOpenMPRuntime::emitCancellationPointCall(
5580 CodeGenFunction &CGF, SourceLocation Loc,
5581 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005582 if (!CGF.HaveInsertPoint())
5583 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005584 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5585 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005586 if (auto *OMPRegionInfo =
5587 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005588 // For 'cancellation point taskgroup', the task region info may not have a
5589 // cancel. This may instead happen in another adjacent task.
5590 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005591 llvm::Value *Args[] = {
5592 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5593 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005594 // Ignore return result until untied tasks are supported.
5595 auto *Result = CGF.EmitRuntimeCall(
5596 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5597 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005598 // exit from construct;
5599 // }
5600 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5601 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5602 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5603 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5604 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005605 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005606 auto CancelDest =
5607 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005608 CGF.EmitBranchThroughCleanup(CancelDest);
5609 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5610 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005611 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005612}
5613
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005614void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005615 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005616 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005617 if (!CGF.HaveInsertPoint())
5618 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005619 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5620 // kmp_int32 cncl_kind);
5621 if (auto *OMPRegionInfo =
5622 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005623 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5624 PrePostActionTy &) {
5625 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005626 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005627 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005628 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5629 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005630 auto *Result = CGF.EmitRuntimeCall(
5631 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005632 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005633 // exit from construct;
5634 // }
5635 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5636 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5637 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5638 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5639 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005640 // exit from construct;
5641 auto CancelDest =
5642 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5643 CGF.EmitBranchThroughCleanup(CancelDest);
5644 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5645 };
5646 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005647 emitOMPIfClause(CGF, IfCond, ThenGen,
5648 [](CodeGenFunction &, PrePostActionTy &) {});
5649 else {
5650 RegionCodeGenTy ThenRCG(ThenGen);
5651 ThenRCG(CGF);
5652 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005653 }
5654}
Samuel Antaobed3c462015-10-02 16:14:20 +00005655
Samuel Antaoee8fb302016-01-06 13:42:12 +00005656/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005657/// consists of the file and device IDs as well as line number associated with
5658/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005659static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5660 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005661 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005662
5663 auto &SM = C.getSourceManager();
5664
5665 // The loc should be always valid and have a file ID (the user cannot use
5666 // #pragma directives in macros)
5667
5668 assert(Loc.isValid() && "Source location is expected to be always valid.");
5669 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5670
5671 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5672 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5673
5674 llvm::sys::fs::UniqueID ID;
5675 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5676 llvm_unreachable("Source file with target region no longer exists!");
5677
5678 DeviceID = ID.getDevice();
5679 FileID = ID.getFile();
5680 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005681}
5682
5683void CGOpenMPRuntime::emitTargetOutlinedFunction(
5684 const OMPExecutableDirective &D, StringRef ParentName,
5685 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005686 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005687 assert(!ParentName.empty() && "Invalid target region parent name!");
5688
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005689 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5690 IsOffloadEntry, CodeGen);
5691}
5692
5693void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5694 const OMPExecutableDirective &D, StringRef ParentName,
5695 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5696 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005697 // Create a unique name for the entry function using the source location
5698 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005699 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005700 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005701 //
5702 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005703 // mangled name of the function that encloses the target region and BB is the
5704 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005705
5706 unsigned DeviceID;
5707 unsigned FileID;
5708 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005709 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005710 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005711 SmallString<64> EntryFnName;
5712 {
5713 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005714 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5715 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005716 }
5717
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005718 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5719
Samuel Antaobed3c462015-10-02 16:14:20 +00005720 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005721 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005722 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005723
Samuel Antao6d004262016-06-16 18:39:34 +00005724 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005725
5726 // If this target outline function is not an offload entry, we don't need to
5727 // register it.
5728 if (!IsOffloadEntry)
5729 return;
5730
5731 // The target region ID is used by the runtime library to identify the current
5732 // target region, so it only has to be unique and not necessarily point to
5733 // anything. It could be the pointer to the outlined function that implements
5734 // the target region, but we aren't using that so that the compiler doesn't
5735 // need to keep that, and could therefore inline the host function if proven
5736 // worthwhile during optimization. In the other hand, if emitting code for the
5737 // device, the ID has to be the function address so that it can retrieved from
5738 // the offloading entry and launched by the runtime library. We also mark the
5739 // outlined function to have external linkage in case we are emitting code for
5740 // the device, because these functions will be entry points to the device.
5741
5742 if (CGM.getLangOpts().OpenMPIsDevice) {
5743 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5744 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5745 } else
5746 OutlinedFnID = new llvm::GlobalVariable(
5747 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5748 llvm::GlobalValue::PrivateLinkage,
5749 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5750
5751 // Register the information for the entry associated with this target region.
5752 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005753 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5754 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005755}
5756
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005757/// discard all CompoundStmts intervening between two constructs
5758static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5759 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5760 Body = CS->body_front();
5761
5762 return Body;
5763}
5764
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005765/// Emit the number of teams for a target directive. Inspect the num_teams
5766/// clause associated with a teams construct combined or closely nested
5767/// with the target directive.
5768///
5769/// Emit a team of size one for directives such as 'target parallel' that
5770/// have no associated teams construct.
5771///
5772/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005773static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005774emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5775 CodeGenFunction &CGF,
5776 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005777
5778 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5779 "teams directive expected to be "
5780 "emitted only for the host!");
5781
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005782 auto &Bld = CGF.Builder;
5783
5784 // If the target directive is combined with a teams directive:
5785 // Return the value in the num_teams clause, if any.
5786 // Otherwise, return 0 to denote the runtime default.
5787 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5788 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5789 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5790 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5791 /*IgnoreResultAssign*/ true);
5792 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5793 /*IsSigned=*/true);
5794 }
5795
5796 // The default value is 0.
5797 return Bld.getInt32(0);
5798 }
5799
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005800 // If the target directive is combined with a parallel directive but not a
5801 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005802 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5803 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005804
5805 // If the current target region has a teams region enclosed, we need to get
5806 // the number of teams to pass to the runtime function call. This is done
5807 // by generating the expression in a inlined region. This is required because
5808 // the expression is captured in the enclosing target environment when the
5809 // teams directive is not combined with target.
5810
5811 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5812
5813 // FIXME: Accommodate other combined directives with teams when they become
5814 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005815 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5816 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005817 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5818 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5819 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5820 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005821 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5822 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005823 }
5824
5825 // If we have an enclosed teams directive but no num_teams clause we use
5826 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005827 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005828 }
5829
5830 // No teams associated with the directive.
5831 return nullptr;
5832}
5833
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005834/// Emit the number of threads for a target directive. Inspect the
5835/// thread_limit clause associated with a teams construct combined or closely
5836/// nested with the target directive.
5837///
5838/// Emit the num_threads clause for directives such as 'target parallel' that
5839/// have no associated teams construct.
5840///
5841/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005842static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005843emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5844 CodeGenFunction &CGF,
5845 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005846
5847 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5848 "teams directive expected to be "
5849 "emitted only for the host!");
5850
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005851 auto &Bld = CGF.Builder;
5852
5853 //
5854 // If the target directive is combined with a teams directive:
5855 // Return the value in the thread_limit clause, if any.
5856 //
5857 // If the target directive is combined with a parallel directive:
5858 // Return the value in the num_threads clause, if any.
5859 //
5860 // If both clauses are set, select the minimum of the two.
5861 //
5862 // If neither teams or parallel combined directives set the number of threads
5863 // in a team, return 0 to denote the runtime default.
5864 //
5865 // If this is not a teams directive return nullptr.
5866
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005867 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5868 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005869 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5870 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005871 llvm::Value *ThreadLimitVal = nullptr;
5872
5873 if (const auto *ThreadLimitClause =
5874 D.getSingleClause<OMPThreadLimitClause>()) {
5875 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5876 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5877 /*IgnoreResultAssign*/ true);
5878 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5879 /*IsSigned=*/true);
5880 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005881
5882 if (const auto *NumThreadsClause =
5883 D.getSingleClause<OMPNumThreadsClause>()) {
5884 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5885 llvm::Value *NumThreads =
5886 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5887 /*IgnoreResultAssign*/ true);
5888 NumThreadsVal =
5889 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5890 }
5891
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005892 // Select the lesser of thread_limit and num_threads.
5893 if (NumThreadsVal)
5894 ThreadLimitVal = ThreadLimitVal
5895 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5896 ThreadLimitVal),
5897 NumThreadsVal, ThreadLimitVal)
5898 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005899
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005900 // Set default value passed to the runtime if either teams or a target
5901 // parallel type directive is found but no clause is specified.
5902 if (!ThreadLimitVal)
5903 ThreadLimitVal = DefaultThreadLimitVal;
5904
5905 return ThreadLimitVal;
5906 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005907
Samuel Antaob68e2db2016-03-03 16:20:23 +00005908 // If the current target region has a teams region enclosed, we need to get
5909 // the thread limit to pass to the runtime function call. This is done
5910 // by generating the expression in a inlined region. This is required because
5911 // the expression is captured in the enclosing target environment when the
5912 // teams directive is not combined with target.
5913
5914 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5915
5916 // FIXME: Accommodate other combined directives with teams when they become
5917 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005918 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5919 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005920 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5921 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5922 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5923 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5924 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5925 /*IsSigned=*/true);
5926 }
5927
5928 // If we have an enclosed teams directive but no thread_limit clause we use
5929 // the default value 0.
5930 return CGF.Builder.getInt32(0);
5931 }
5932
5933 // No teams associated with the directive.
5934 return nullptr;
5935}
5936
Samuel Antao86ace552016-04-27 22:40:57 +00005937namespace {
5938// \brief Utility to handle information from clauses associated with a given
5939// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5940// It provides a convenient interface to obtain the information and generate
5941// code for that information.
5942class MappableExprsHandler {
5943public:
5944 /// \brief Values for bit flags used to specify the mapping type for
5945 /// offloading.
5946 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005947 /// \brief Allocate memory on the device and move data from host to device.
5948 OMP_MAP_TO = 0x01,
5949 /// \brief Allocate memory on the device and move data from device to host.
5950 OMP_MAP_FROM = 0x02,
5951 /// \brief Always perform the requested mapping action on the element, even
5952 /// if it was already mapped before.
5953 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005954 /// \brief Delete the element from the device environment, ignoring the
5955 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005956 OMP_MAP_DELETE = 0x08,
5957 /// \brief The element being mapped is a pointer, therefore the pointee
5958 /// should be mapped as well.
5959 OMP_MAP_IS_PTR = 0x10,
5960 /// \brief This flags signals that an argument is the first one relating to
5961 /// a map/private clause expression. For some cases a single
5962 /// map/privatization results in multiple arguments passed to the runtime
5963 /// library.
5964 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005965 /// \brief Signal that the runtime library has to return the device pointer
5966 /// in the current position for the data being mapped.
5967 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005968 /// \brief This flag signals that the reference being passed is a pointer to
5969 /// private data.
5970 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005971 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005972 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005973 };
5974
Samuel Antaocc10b852016-07-28 14:23:26 +00005975 /// Class that associates information with a base pointer to be passed to the
5976 /// runtime library.
5977 class BasePointerInfo {
5978 /// The base pointer.
5979 llvm::Value *Ptr = nullptr;
5980 /// The base declaration that refers to this device pointer, or null if
5981 /// there is none.
5982 const ValueDecl *DevPtrDecl = nullptr;
5983
5984 public:
5985 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5986 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5987 llvm::Value *operator*() const { return Ptr; }
5988 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5989 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5990 };
5991
5992 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005993 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5994 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5995
5996private:
5997 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005998 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005999
6000 /// \brief Function the directive is being generated for.
6001 CodeGenFunction &CGF;
6002
Samuel Antaod486f842016-05-26 16:53:38 +00006003 /// \brief Set of all first private variables in the current directive.
6004 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6005
Samuel Antao6890b092016-07-28 14:25:09 +00006006 /// Map between device pointer declarations and their expression components.
6007 /// The key value for declarations in 'this' is null.
6008 llvm::DenseMap<
6009 const ValueDecl *,
6010 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6011 DevPointersMap;
6012
Samuel Antao86ace552016-04-27 22:40:57 +00006013 llvm::Value *getExprTypeSize(const Expr *E) const {
6014 auto ExprTy = E->getType().getCanonicalType();
6015
6016 // Reference types are ignored for mapping purposes.
6017 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6018 ExprTy = RefTy->getPointeeType().getCanonicalType();
6019
6020 // Given that an array section is considered a built-in type, we need to
6021 // do the calculation based on the length of the section instead of relying
6022 // on CGF.getTypeSize(E->getType()).
6023 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6024 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6025 OAE->getBase()->IgnoreParenImpCasts())
6026 .getCanonicalType();
6027
6028 // If there is no length associated with the expression, that means we
6029 // are using the whole length of the base.
6030 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6031 return CGF.getTypeSize(BaseTy);
6032
6033 llvm::Value *ElemSize;
6034 if (auto *PTy = BaseTy->getAs<PointerType>())
6035 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6036 else {
6037 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6038 assert(ATy && "Expecting array type if not a pointer type.");
6039 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6040 }
6041
6042 // If we don't have a length at this point, that is because we have an
6043 // array section with a single element.
6044 if (!OAE->getLength())
6045 return ElemSize;
6046
6047 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6048 LengthVal =
6049 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6050 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6051 }
6052 return CGF.getTypeSize(ExprTy);
6053 }
6054
6055 /// \brief Return the corresponding bits for a given map clause modifier. Add
6056 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006057 /// map as the first one of a series of maps that relate to the same map
6058 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00006059 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6060 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00006061 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006062 unsigned Bits = 0u;
6063 switch (MapType) {
6064 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006065 case OMPC_MAP_release:
6066 // alloc and release is the default behavior in the runtime library, i.e.
6067 // if we don't pass any bits alloc/release that is what the runtime is
6068 // going to do. Therefore, we don't need to signal anything for these two
6069 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006070 break;
6071 case OMPC_MAP_to:
6072 Bits = OMP_MAP_TO;
6073 break;
6074 case OMPC_MAP_from:
6075 Bits = OMP_MAP_FROM;
6076 break;
6077 case OMPC_MAP_tofrom:
6078 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6079 break;
6080 case OMPC_MAP_delete:
6081 Bits = OMP_MAP_DELETE;
6082 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006083 default:
6084 llvm_unreachable("Unexpected map type!");
6085 break;
6086 }
6087 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00006088 Bits |= OMP_MAP_IS_PTR;
6089 if (AddIsFirstFlag)
6090 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00006091 if (MapTypeModifier == OMPC_MAP_always)
6092 Bits |= OMP_MAP_ALWAYS;
6093 return Bits;
6094 }
6095
6096 /// \brief Return true if the provided expression is a final array section. A
6097 /// final array section, is one whose length can't be proved to be one.
6098 bool isFinalArraySectionExpression(const Expr *E) const {
6099 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6100
6101 // It is not an array section and therefore not a unity-size one.
6102 if (!OASE)
6103 return false;
6104
6105 // An array section with no colon always refer to a single element.
6106 if (OASE->getColonLoc().isInvalid())
6107 return false;
6108
6109 auto *Length = OASE->getLength();
6110
6111 // If we don't have a length we have to check if the array has size 1
6112 // for this dimension. Also, we should always expect a length if the
6113 // base type is pointer.
6114 if (!Length) {
6115 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6116 OASE->getBase()->IgnoreParenImpCasts())
6117 .getCanonicalType();
6118 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6119 return ATy->getSize().getSExtValue() != 1;
6120 // If we don't have a constant dimension length, we have to consider
6121 // the current section as having any size, so it is not necessarily
6122 // unitary. If it happen to be unity size, that's user fault.
6123 return true;
6124 }
6125
6126 // Check if the length evaluates to 1.
6127 llvm::APSInt ConstLength;
6128 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6129 return true; // Can have more that size 1.
6130
6131 return ConstLength.getSExtValue() != 1;
6132 }
6133
6134 /// \brief Generate the base pointers, section pointers, sizes and map type
6135 /// bits for the provided map type, map modifier, and expression components.
6136 /// \a IsFirstComponent should be set to true if the provided set of
6137 /// components is the first associated with a capture.
6138 void generateInfoForComponentList(
6139 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6140 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006141 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006142 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
6143 bool IsFirstComponentList) const {
6144
6145 // The following summarizes what has to be generated for each map and the
6146 // types bellow. The generated information is expressed in this order:
6147 // base pointer, section pointer, size, flags
6148 // (to add to the ones that come from the map type and modifier).
6149 //
6150 // double d;
6151 // int i[100];
6152 // float *p;
6153 //
6154 // struct S1 {
6155 // int i;
6156 // float f[50];
6157 // }
6158 // struct S2 {
6159 // int i;
6160 // float f[50];
6161 // S1 s;
6162 // double *p;
6163 // struct S2 *ps;
6164 // }
6165 // S2 s;
6166 // S2 *ps;
6167 //
6168 // map(d)
6169 // &d, &d, sizeof(double), noflags
6170 //
6171 // map(i)
6172 // &i, &i, 100*sizeof(int), noflags
6173 //
6174 // map(i[1:23])
6175 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6176 //
6177 // map(p)
6178 // &p, &p, sizeof(float*), noflags
6179 //
6180 // map(p[1:24])
6181 // p, &p[1], 24*sizeof(float), noflags
6182 //
6183 // map(s)
6184 // &s, &s, sizeof(S2), noflags
6185 //
6186 // map(s.i)
6187 // &s, &(s.i), sizeof(int), noflags
6188 //
6189 // map(s.s.f)
6190 // &s, &(s.i.f), 50*sizeof(int), noflags
6191 //
6192 // map(s.p)
6193 // &s, &(s.p), sizeof(double*), noflags
6194 //
6195 // map(s.p[:22], s.a s.b)
6196 // &s, &(s.p), sizeof(double*), noflags
6197 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
6198 //
6199 // map(s.ps)
6200 // &s, &(s.ps), sizeof(S2*), noflags
6201 //
6202 // map(s.ps->s.i)
6203 // &s, &(s.ps), sizeof(S2*), noflags
6204 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
6205 //
6206 // map(s.ps->ps)
6207 // &s, &(s.ps), sizeof(S2*), noflags
6208 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6209 //
6210 // map(s.ps->ps->ps)
6211 // &s, &(s.ps), sizeof(S2*), noflags
6212 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6213 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6214 //
6215 // map(s.ps->ps->s.f[:22])
6216 // &s, &(s.ps), sizeof(S2*), noflags
6217 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6218 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
6219 //
6220 // map(ps)
6221 // &ps, &ps, sizeof(S2*), noflags
6222 //
6223 // map(ps->i)
6224 // ps, &(ps->i), sizeof(int), noflags
6225 //
6226 // map(ps->s.f)
6227 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6228 //
6229 // map(ps->p)
6230 // ps, &(ps->p), sizeof(double*), noflags
6231 //
6232 // map(ps->p[:22])
6233 // ps, &(ps->p), sizeof(double*), noflags
6234 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
6235 //
6236 // map(ps->ps)
6237 // ps, &(ps->ps), sizeof(S2*), noflags
6238 //
6239 // map(ps->ps->s.i)
6240 // ps, &(ps->ps), sizeof(S2*), noflags
6241 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
6242 //
6243 // map(ps->ps->ps)
6244 // ps, &(ps->ps), sizeof(S2*), noflags
6245 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6246 //
6247 // map(ps->ps->ps->ps)
6248 // ps, &(ps->ps), sizeof(S2*), noflags
6249 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6250 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6251 //
6252 // map(ps->ps->ps->s.f[:22])
6253 // ps, &(ps->ps), sizeof(S2*), noflags
6254 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6255 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
6256 // extra_flag
6257
6258 // Track if the map information being generated is the first for a capture.
6259 bool IsCaptureFirstInfo = IsFirstComponentList;
6260
6261 // Scan the components from the base to the complete expression.
6262 auto CI = Components.rbegin();
6263 auto CE = Components.rend();
6264 auto I = CI;
6265
6266 // Track if the map information being generated is the first for a list of
6267 // components.
6268 bool IsExpressionFirstInfo = true;
6269 llvm::Value *BP = nullptr;
6270
6271 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6272 // The base is the 'this' pointer. The content of the pointer is going
6273 // to be the base of the field being mapped.
6274 BP = CGF.EmitScalarExpr(ME->getBase());
6275 } else {
6276 // The base is the reference to the variable.
6277 // BP = &Var.
6278 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
6279 .getPointer();
6280
6281 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006282 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006283 // reference. References are ignored for mapping purposes.
6284 QualType Ty =
6285 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6286 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6287 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006288 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006289 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006290 .getPointer();
6291
6292 // We do not need to generate individual map information for the
6293 // pointer, it can be associated with the combined storage.
6294 ++I;
6295 }
6296 }
6297
6298 for (; I != CE; ++I) {
6299 auto Next = std::next(I);
6300
6301 // We need to generate the addresses and sizes if this is the last
6302 // component, if the component is a pointer or if it is an array section
6303 // whose length can't be proved to be one. If this is a pointer, it
6304 // becomes the base address for the following components.
6305
6306 // A final array section, is one whose length can't be proved to be one.
6307 bool IsFinalArraySection =
6308 isFinalArraySectionExpression(I->getAssociatedExpression());
6309
6310 // Get information on whether the element is a pointer. Have to do a
6311 // special treatment for array sections given that they are built-in
6312 // types.
6313 const auto *OASE =
6314 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6315 bool IsPointer =
6316 (OASE &&
6317 OMPArraySectionExpr::getBaseOriginalType(OASE)
6318 .getCanonicalType()
6319 ->isAnyPointerType()) ||
6320 I->getAssociatedExpression()->getType()->isAnyPointerType();
6321
6322 if (Next == CE || IsPointer || IsFinalArraySection) {
6323
6324 // If this is not the last component, we expect the pointer to be
6325 // associated with an array expression or member expression.
6326 assert((Next == CE ||
6327 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6328 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6329 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6330 "Unexpected expression");
6331
Samuel Antao86ace552016-04-27 22:40:57 +00006332 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
6333 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6334
Samuel Antao03a3cec2016-07-27 22:52:16 +00006335 // If we have a member expression and the current component is a
6336 // reference, we have to map the reference too. Whenever we have a
6337 // reference, the section that reference refers to is going to be a
6338 // load instruction from the storage assigned to the reference.
6339 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6340 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6341 auto *LI = cast<llvm::LoadInst>(LB);
6342 auto *RefAddr = LI->getPointerOperand();
6343
6344 BasePointers.push_back(BP);
6345 Pointers.push_back(RefAddr);
6346 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6347 Types.push_back(getMapTypeBits(
6348 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
6349 !IsExpressionFirstInfo, IsCaptureFirstInfo));
6350 IsExpressionFirstInfo = false;
6351 IsCaptureFirstInfo = false;
6352 // The reference will be the next base address.
6353 BP = RefAddr;
6354 }
6355
6356 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006357 Pointers.push_back(LB);
6358 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006359
Samuel Antao6782e942016-05-26 16:48:10 +00006360 // We need to add a pointer flag for each map that comes from the
6361 // same expression except for the first one. We also need to signal
6362 // this map is the first one that relates with the current capture
6363 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00006364 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
6365 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00006366 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006367
6368 // If we have a final array section, we are done with this expression.
6369 if (IsFinalArraySection)
6370 break;
6371
6372 // The pointer becomes the base for the next element.
6373 if (Next != CE)
6374 BP = LB;
6375
6376 IsExpressionFirstInfo = false;
6377 IsCaptureFirstInfo = false;
6378 continue;
6379 }
6380 }
6381 }
6382
Samuel Antaod486f842016-05-26 16:53:38 +00006383 /// \brief Return the adjusted map modifiers if the declaration a capture
6384 /// refers to appears in a first-private clause. This is expected to be used
6385 /// only with directives that start with 'target'.
6386 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6387 unsigned CurrentModifiers) {
6388 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6389
6390 // A first private variable captured by reference will use only the
6391 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6392 // declaration is known as first-private in this handler.
6393 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6394 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
6395 MappableExprsHandler::OMP_MAP_TO;
6396
6397 // We didn't modify anything.
6398 return CurrentModifiers;
6399 }
6400
Samuel Antao86ace552016-04-27 22:40:57 +00006401public:
6402 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006403 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006404 // Extract firstprivate clause information.
6405 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6406 for (const auto *D : C->varlists())
6407 FirstPrivateDecls.insert(
6408 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006409 // Extract device pointer clause information.
6410 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6411 for (auto L : C->component_lists())
6412 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006413 }
Samuel Antao86ace552016-04-27 22:40:57 +00006414
6415 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006416 /// types for the extracted mappable expressions. Also, for each item that
6417 /// relates with a device pointer, a pair of the relevant declaration and
6418 /// index where it occurs is appended to the device pointers info array.
6419 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006420 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6421 MapFlagsArrayTy &Types) const {
6422 BasePointers.clear();
6423 Pointers.clear();
6424 Sizes.clear();
6425 Types.clear();
6426
6427 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006428 /// Kind that defines how a device pointer has to be returned.
6429 enum ReturnPointerKind {
6430 // Don't have to return any pointer.
6431 RPK_None,
6432 // Pointer is the base of the declaration.
6433 RPK_Base,
6434 // Pointer is a member of the base declaration - 'this'
6435 RPK_Member,
6436 // Pointer is a reference and a member of the base declaration - 'this'
6437 RPK_MemberReference,
6438 };
Samuel Antao86ace552016-04-27 22:40:57 +00006439 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006440 OpenMPMapClauseKind MapType;
6441 OpenMPMapClauseKind MapTypeModifier;
6442 ReturnPointerKind ReturnDevicePointer;
6443
6444 MapInfo()
6445 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
6446 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00006447 MapInfo(
6448 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6449 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6450 ReturnPointerKind ReturnDevicePointer)
6451 : Components(Components), MapType(MapType),
6452 MapTypeModifier(MapTypeModifier),
6453 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006454 };
6455
6456 // We have to process the component lists that relate with the same
6457 // declaration in a single chunk so that we can generate the map flags
6458 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006459 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006460
6461 // Helper function to fill the information map for the different supported
6462 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006463 auto &&InfoGen = [&Info](
6464 const ValueDecl *D,
6465 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6466 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006467 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006468 const ValueDecl *VD =
6469 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
6470 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
6471 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006472
Paul Robinson78fb1322016-08-01 22:12:46 +00006473 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006474 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006475 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006476 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
6477 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006478 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006479 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006480 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
6481 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006482 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006483 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006484 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
6485 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00006486
Samuel Antaocc10b852016-07-28 14:23:26 +00006487 // Look at the use_device_ptr clause information and mark the existing map
6488 // entries as such. If there is no map information for an entry in the
6489 // use_device_ptr list, we create one with map type 'alloc' and zero size
6490 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006491 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006492 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006493 for (auto L : C->component_lists()) {
6494 assert(!L.second.empty() && "Not expecting empty list of components!");
6495 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6496 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6497 auto *IE = L.second.back().getAssociatedExpression();
6498 // If the first component is a member expression, we have to look into
6499 // 'this', which maps to null in the map of map information. Otherwise
6500 // look directly for the information.
6501 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6502
6503 // We potentially have map information for this declaration already.
6504 // Look for the first set of components that refer to it.
6505 if (It != Info.end()) {
6506 auto CI = std::find_if(
6507 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6508 return MI.Components.back().getAssociatedDeclaration() == VD;
6509 });
6510 // If we found a map entry, signal that the pointer has to be returned
6511 // and move on to the next declaration.
6512 if (CI != It->second.end()) {
6513 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6514 ? (VD->getType()->isReferenceType()
6515 ? MapInfo::RPK_MemberReference
6516 : MapInfo::RPK_Member)
6517 : MapInfo::RPK_Base;
6518 continue;
6519 }
6520 }
6521
6522 // We didn't find any match in our map information - generate a zero
6523 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006524 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006525 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006526 this->CGF
6527 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006528 .getScalarVal();
6529 BasePointers.push_back({Ptr, VD});
6530 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006531 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00006532 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6533 }
6534
Samuel Antao86ace552016-04-27 22:40:57 +00006535 for (auto &M : Info) {
6536 // We need to know when we generate information for the first component
6537 // associated with a capture, because the mapping flags depend on it.
6538 bool IsFirstComponentList = true;
6539 for (MapInfo &L : M.second) {
6540 assert(!L.Components.empty() &&
6541 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006542
6543 // Remember the current base pointer index.
6544 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006545 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00006546 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
6547 L.Components, BasePointers, Pointers,
6548 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00006549
6550 // If this entry relates with a device pointer, set the relevant
6551 // declaration and add the 'return pointer' flag.
6552 if (IsFirstComponentList &&
6553 L.ReturnDevicePointer != MapInfo::RPK_None) {
6554 // If the pointer is not the base of the map, we need to skip the
6555 // base. If it is a reference in a member field, we also need to skip
6556 // the map of the reference.
6557 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6558 ++CurrentBasePointersIdx;
6559 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6560 ++CurrentBasePointersIdx;
6561 }
6562 assert(BasePointers.size() > CurrentBasePointersIdx &&
6563 "Unexpected number of mapped base pointers.");
6564
6565 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6566 assert(RelevantVD &&
6567 "No relevant declaration related with device pointer??");
6568
6569 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6570 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6571 }
Samuel Antao86ace552016-04-27 22:40:57 +00006572 IsFirstComponentList = false;
6573 }
6574 }
6575 }
6576
6577 /// \brief Generate the base pointers, section pointers, sizes and map types
6578 /// associated to a given capture.
6579 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006580 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006581 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006582 MapValuesArrayTy &Pointers,
6583 MapValuesArrayTy &Sizes,
6584 MapFlagsArrayTy &Types) const {
6585 assert(!Cap->capturesVariableArrayType() &&
6586 "Not expecting to generate map info for a variable array type!");
6587
6588 BasePointers.clear();
6589 Pointers.clear();
6590 Sizes.clear();
6591 Types.clear();
6592
Samuel Antao6890b092016-07-28 14:25:09 +00006593 // We need to know when we generating information for the first component
6594 // associated with a capture, because the mapping flags depend on it.
6595 bool IsFirstComponentList = true;
6596
Samuel Antao86ace552016-04-27 22:40:57 +00006597 const ValueDecl *VD =
6598 Cap->capturesThis()
6599 ? nullptr
6600 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6601
Samuel Antao6890b092016-07-28 14:25:09 +00006602 // If this declaration appears in a is_device_ptr clause we just have to
6603 // pass the pointer by value. If it is a reference to a declaration, we just
6604 // pass its value, otherwise, if it is a member expression, we need to map
6605 // 'to' the field.
6606 if (!VD) {
6607 auto It = DevPointersMap.find(VD);
6608 if (It != DevPointersMap.end()) {
6609 for (auto L : It->second) {
6610 generateInfoForComponentList(
6611 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
6612 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
6613 IsFirstComponentList = false;
6614 }
6615 return;
6616 }
6617 } else if (DevPointersMap.count(VD)) {
6618 BasePointers.push_back({Arg, VD});
6619 Pointers.push_back(Arg);
6620 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6621 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6622 return;
6623 }
6624
Paul Robinson78fb1322016-08-01 22:12:46 +00006625 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006626 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006627 for (auto L : C->decl_component_lists(VD)) {
6628 assert(L.first == VD &&
6629 "We got information for the wrong declaration??");
6630 assert(!L.second.empty() &&
6631 "Not expecting declaration with no component lists.");
6632 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
6633 L.second, BasePointers, Pointers, Sizes,
6634 Types, IsFirstComponentList);
6635 IsFirstComponentList = false;
6636 }
6637
6638 return;
6639 }
Samuel Antaod486f842016-05-26 16:53:38 +00006640
6641 /// \brief Generate the default map information for a given capture \a CI,
6642 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006643 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6644 const FieldDecl &RI, llvm::Value *CV,
6645 MapBaseValuesArrayTy &CurBasePointers,
6646 MapValuesArrayTy &CurPointers,
6647 MapValuesArrayTy &CurSizes,
6648 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006649
6650 // Do the default mapping.
6651 if (CI.capturesThis()) {
6652 CurBasePointers.push_back(CV);
6653 CurPointers.push_back(CV);
6654 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6655 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6656 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006657 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006658 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006659 CurBasePointers.push_back(CV);
6660 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006661 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006662 // We have to signal to the runtime captures passed by value that are
6663 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00006664 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006665 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6666 } else {
6667 // Pointers are implicitly mapped with a zero size and no flags
6668 // (other than first map that is added for all implicit maps).
6669 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006670 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6671 }
6672 } else {
6673 assert(CI.capturesVariable() && "Expected captured reference.");
6674 CurBasePointers.push_back(CV);
6675 CurPointers.push_back(CV);
6676
6677 const ReferenceType *PtrTy =
6678 cast<ReferenceType>(RI.getType().getTypePtr());
6679 QualType ElementType = PtrTy->getPointeeType();
6680 CurSizes.push_back(CGF.getTypeSize(ElementType));
6681 // The default map type for a scalar/complex type is 'to' because by
6682 // default the value doesn't have to be retrieved. For an aggregate
6683 // type, the default is 'tofrom'.
6684 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006685 ? (OMP_MAP_TO | OMP_MAP_FROM)
6686 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006687
6688 // If we have a capture by reference we may need to add the private
6689 // pointer flag if the base declaration shows in some first-private
6690 // clause.
6691 CurMapTypes.back() =
6692 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6693 }
6694 // Every default map produces a single argument, so, it is always the
6695 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00006696 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00006697 }
Samuel Antao86ace552016-04-27 22:40:57 +00006698};
Samuel Antaodf158d52016-04-27 22:58:19 +00006699
6700enum OpenMPOffloadingReservedDeviceIDs {
6701 /// \brief Device ID if the device was not defined, runtime should get it
6702 /// from environment variables in the spec.
6703 OMP_DEVICEID_UNDEF = -1,
6704};
6705} // anonymous namespace
6706
6707/// \brief Emit the arrays used to pass the captures and map information to the
6708/// offloading runtime library. If there is no map or capture information,
6709/// return nullptr by reference.
6710static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006711emitOffloadingArrays(CodeGenFunction &CGF,
6712 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006713 MappableExprsHandler::MapValuesArrayTy &Pointers,
6714 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006715 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6716 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006717 auto &CGM = CGF.CGM;
6718 auto &Ctx = CGF.getContext();
6719
Samuel Antaocc10b852016-07-28 14:23:26 +00006720 // Reset the array information.
6721 Info.clearArrayInfo();
6722 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006723
Samuel Antaocc10b852016-07-28 14:23:26 +00006724 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006725 // Detect if we have any capture size requiring runtime evaluation of the
6726 // size so that a constant array could be eventually used.
6727 bool hasRuntimeEvaluationCaptureSize = false;
6728 for (auto *S : Sizes)
6729 if (!isa<llvm::Constant>(S)) {
6730 hasRuntimeEvaluationCaptureSize = true;
6731 break;
6732 }
6733
Samuel Antaocc10b852016-07-28 14:23:26 +00006734 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006735 QualType PointerArrayType =
6736 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6737 /*IndexTypeQuals=*/0);
6738
Samuel Antaocc10b852016-07-28 14:23:26 +00006739 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006740 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006741 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006742 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6743
6744 // If we don't have any VLA types or other types that require runtime
6745 // evaluation, we can use a constant array for the map sizes, otherwise we
6746 // need to fill up the arrays as we do for the pointers.
6747 if (hasRuntimeEvaluationCaptureSize) {
6748 QualType SizeArrayType = Ctx.getConstantArrayType(
6749 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6750 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006751 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006752 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6753 } else {
6754 // We expect all the sizes to be constant, so we collect them to create
6755 // a constant array.
6756 SmallVector<llvm::Constant *, 16> ConstSizes;
6757 for (auto S : Sizes)
6758 ConstSizes.push_back(cast<llvm::Constant>(S));
6759
6760 auto *SizesArrayInit = llvm::ConstantArray::get(
6761 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6762 auto *SizesArrayGbl = new llvm::GlobalVariable(
6763 CGM.getModule(), SizesArrayInit->getType(),
6764 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6765 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006766 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006767 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006768 }
6769
6770 // The map types are always constant so we don't need to generate code to
6771 // fill arrays. Instead, we create an array constant.
6772 llvm::Constant *MapTypesArrayInit =
6773 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6774 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6775 CGM.getModule(), MapTypesArrayInit->getType(),
6776 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6777 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006778 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006779 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006780
Samuel Antaocc10b852016-07-28 14:23:26 +00006781 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6782 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006783 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006784 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6785 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006786 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6787 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006788 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6789 CGF.Builder.CreateStore(BPVal, BPAddr);
6790
Samuel Antaocc10b852016-07-28 14:23:26 +00006791 if (Info.requiresDevicePointerInfo())
6792 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6793 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6794
Samuel Antaodf158d52016-04-27 22:58:19 +00006795 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006796 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006797 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6798 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006799 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6800 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006801 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6802 CGF.Builder.CreateStore(PVal, PAddr);
6803
6804 if (hasRuntimeEvaluationCaptureSize) {
6805 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006806 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6807 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006808 /*Idx0=*/0,
6809 /*Idx1=*/i);
6810 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6811 CGF.Builder.CreateStore(
6812 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6813 SAddr);
6814 }
6815 }
6816 }
6817}
6818/// \brief Emit the arguments to be passed to the runtime library based on the
6819/// arrays of pointers, sizes and map types.
6820static void emitOffloadingArraysArgument(
6821 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6822 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006823 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006824 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006825 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006826 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006827 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6828 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006829 /*Idx0=*/0, /*Idx1=*/0);
6830 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006831 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6832 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006833 /*Idx0=*/0,
6834 /*Idx1=*/0);
6835 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006836 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006837 /*Idx0=*/0, /*Idx1=*/0);
6838 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006839 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6840 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006841 /*Idx0=*/0,
6842 /*Idx1=*/0);
6843 } else {
6844 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6845 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6846 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6847 MapTypesArrayArg =
6848 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6849 }
Samuel Antao86ace552016-04-27 22:40:57 +00006850}
6851
Samuel Antaobed3c462015-10-02 16:14:20 +00006852void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6853 const OMPExecutableDirective &D,
6854 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006855 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006856 const Expr *IfCond, const Expr *Device,
6857 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006858 if (!CGF.HaveInsertPoint())
6859 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006860
Samuel Antaoee8fb302016-01-06 13:42:12 +00006861 assert(OutlinedFn && "Invalid outlined function!");
6862
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006863 auto &Ctx = CGF.getContext();
6864
Samuel Antao86ace552016-04-27 22:40:57 +00006865 // Fill up the arrays with all the captured variables.
6866 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006867 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006868 MappableExprsHandler::MapValuesArrayTy Pointers;
6869 MappableExprsHandler::MapValuesArrayTy Sizes;
6870 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006871
Samuel Antaocc10b852016-07-28 14:23:26 +00006872 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006873 MappableExprsHandler::MapValuesArrayTy CurPointers;
6874 MappableExprsHandler::MapValuesArrayTy CurSizes;
6875 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6876
Samuel Antaod486f842016-05-26 16:53:38 +00006877 // Get mappable expression information.
6878 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006879
6880 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6881 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006882 auto CV = CapturedVars.begin();
6883 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6884 CE = CS.capture_end();
6885 CI != CE; ++CI, ++RI, ++CV) {
6886 StringRef Name;
6887 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00006888
Samuel Antao86ace552016-04-27 22:40:57 +00006889 CurBasePointers.clear();
6890 CurPointers.clear();
6891 CurSizes.clear();
6892 CurMapTypes.clear();
6893
6894 // VLA sizes are passed to the outlined region by copy and do not have map
6895 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006896 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006897 CurBasePointers.push_back(*CV);
6898 CurPointers.push_back(*CV);
6899 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006900 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006901 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6902 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006903 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006904 // If we have any information in the map clause, we use it, otherwise we
6905 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006906 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006907 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006908 if (CurBasePointers.empty())
6909 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6910 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006911 }
Samuel Antao86ace552016-04-27 22:40:57 +00006912 // We expect to have at least an element of information for this capture.
6913 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6914 assert(CurBasePointers.size() == CurPointers.size() &&
6915 CurBasePointers.size() == CurSizes.size() &&
6916 CurBasePointers.size() == CurMapTypes.size() &&
6917 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006918
Samuel Antao86ace552016-04-27 22:40:57 +00006919 // The kernel args are always the first elements of the base pointers
6920 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006921 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006922 // We need to append the results of this capture to what we already have.
6923 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6924 Pointers.append(CurPointers.begin(), CurPointers.end());
6925 Sizes.append(CurSizes.begin(), CurSizes.end());
6926 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006927 }
6928
6929 // Keep track on whether the host function has to be executed.
6930 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006931 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006932 auto OffloadError = CGF.MakeAddrLValue(
6933 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6934 OffloadErrorQType);
6935 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6936 OffloadError);
6937
6938 // Fill up the pointer arrays and transfer execution to the device.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006939 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6940 OutlinedFnID, OffloadError,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006941 &D](CodeGenFunction &CGF, PrePostActionTy &) {
6942 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006943 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006944 TargetDataInfo Info;
6945 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6946 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6947 Info.PointersArray, Info.SizesArray,
6948 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006949
6950 // On top of the arrays that were filled up, the target offloading call
6951 // takes as arguments the device id as well as the host pointer. The host
6952 // pointer is used by the runtime library to identify the current target
6953 // region, so it only has to be unique and not necessarily point to
6954 // anything. It could be the pointer to the outlined function that
6955 // implements the target region, but we aren't using that so that the
6956 // compiler doesn't need to keep that, and could therefore inline the host
6957 // function if proven worthwhile during optimization.
6958
Samuel Antaoee8fb302016-01-06 13:42:12 +00006959 // From this point on, we need to have an ID of the target region defined.
6960 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006961
6962 // Emit device ID if any.
6963 llvm::Value *DeviceID;
6964 if (Device)
6965 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006966 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006967 else
6968 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6969
Samuel Antaodf158d52016-04-27 22:58:19 +00006970 // Emit the number of elements in the offloading arrays.
6971 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6972
Samuel Antaob68e2db2016-03-03 16:20:23 +00006973 // Return value of the runtime offloading call.
6974 llvm::Value *Return;
6975
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006976 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6977 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006978
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006979 // The target region is an outlined function launched by the runtime
6980 // via calls __tgt_target() or __tgt_target_teams().
6981 //
6982 // __tgt_target() launches a target region with one team and one thread,
6983 // executing a serial region. This master thread may in turn launch
6984 // more threads within its team upon encountering a parallel region,
6985 // however, no additional teams can be launched on the device.
6986 //
6987 // __tgt_target_teams() launches a target region with one or more teams,
6988 // each with one or more threads. This call is required for target
6989 // constructs such as:
6990 // 'target teams'
6991 // 'target' / 'teams'
6992 // 'target teams distribute parallel for'
6993 // 'target parallel'
6994 // and so on.
6995 //
6996 // Note that on the host and CPU targets, the runtime implementation of
6997 // these calls simply call the outlined function without forking threads.
6998 // The outlined functions themselves have runtime calls to
6999 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7000 // the compiler in emitTeamsCall() and emitParallelCall().
7001 //
7002 // In contrast, on the NVPTX target, the implementation of
7003 // __tgt_target_teams() launches a GPU kernel with the requested number
7004 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007005 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007006 // If we have NumTeams defined this means that we have an enclosed teams
7007 // region. Therefore we also expect to have NumThreads defined. These two
7008 // values should be defined in the presence of a teams directive,
7009 // regardless of having any clauses associated. If the user is using teams
7010 // but no clauses, these two values will be the default that should be
7011 // passed to the runtime library - a 32-bit integer with the value zero.
7012 assert(NumThreads && "Thread limit expression should be available along "
7013 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007014 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007015 DeviceID, OutlinedFnID,
7016 PointerNum, Info.BasePointersArray,
7017 Info.PointersArray, Info.SizesArray,
7018 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007019 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007020 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007021 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007022 } else {
7023 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007024 DeviceID, OutlinedFnID,
7025 PointerNum, Info.BasePointersArray,
7026 Info.PointersArray, Info.SizesArray,
7027 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007028 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007029 OffloadingArgs);
7030 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007031
7032 CGF.EmitStoreOfScalar(Return, OffloadError);
7033 };
7034
Samuel Antaoee8fb302016-01-06 13:42:12 +00007035 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007036 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
7037 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00007038 OffloadError);
7039 };
7040
7041 // If we have a target function ID it means that we need to support
7042 // offloading, otherwise, just execute on the host. We need to execute on host
7043 // regardless of the conditional in the if clause if, e.g., the user do not
7044 // specify target triples.
7045 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007046 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007047 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007048 else {
7049 RegionCodeGenTy ThenRCG(ThenGen);
7050 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007051 }
7052 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007053 RegionCodeGenTy ElseRCG(ElseGen);
7054 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007055 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007056
7057 // Check the error code and execute the host version if required.
7058 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
7059 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
7060 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
7061 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
7062 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7063
7064 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev3c595a62017-08-14 15:01:03 +00007065 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00007066 CGF.EmitBranch(OffloadContBlock);
7067
7068 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007069}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007070
7071void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7072 StringRef ParentName) {
7073 if (!S)
7074 return;
7075
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007076 // Codegen OMP target directives that offload compute to the device.
7077 bool requiresDeviceCodegen =
7078 isa<OMPExecutableDirective>(S) &&
7079 isOpenMPTargetExecutionDirective(
7080 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007081
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007082 if (requiresDeviceCodegen) {
7083 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007084 unsigned DeviceID;
7085 unsigned FileID;
7086 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007087 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007088 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007089
7090 // Is this a target region that should not be emitted as an entry point? If
7091 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007092 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7093 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007094 return;
7095
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007096 switch (S->getStmtClass()) {
7097 case Stmt::OMPTargetDirectiveClass:
7098 CodeGenFunction::EmitOMPTargetDeviceFunction(
7099 CGM, ParentName, cast<OMPTargetDirective>(*S));
7100 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007101 case Stmt::OMPTargetParallelDirectiveClass:
7102 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7103 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7104 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007105 case Stmt::OMPTargetTeamsDirectiveClass:
7106 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7107 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7108 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007109 default:
7110 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7111 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007112 return;
7113 }
7114
7115 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007116 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007117 return;
7118
7119 scanForTargetRegionsFunctions(
7120 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7121 ParentName);
7122 return;
7123 }
7124
7125 // If this is a lambda function, look into its body.
7126 if (auto *L = dyn_cast<LambdaExpr>(S))
7127 S = L->getBody();
7128
7129 // Keep looking for target regions recursively.
7130 for (auto *II : S->children())
7131 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007132}
7133
7134bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7135 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7136
7137 // If emitting code for the host, we do not process FD here. Instead we do
7138 // the normal code generation.
7139 if (!CGM.getLangOpts().OpenMPIsDevice)
7140 return false;
7141
7142 // Try to detect target regions in the function.
7143 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7144
Samuel Antao4b75b872016-12-12 19:26:31 +00007145 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007146 // scanning. Therefore, we signal that this function is completely dealt
7147 // with.
7148 return true;
7149}
7150
7151bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7152 if (!CGM.getLangOpts().OpenMPIsDevice)
7153 return false;
7154
7155 // Check if there are Ctors/Dtors in this declaration and look for target
7156 // regions in it. We use the complete variant to produce the kernel name
7157 // mangling.
7158 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7159 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7160 for (auto *Ctor : RD->ctors()) {
7161 StringRef ParentName =
7162 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7163 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7164 }
7165 auto *Dtor = RD->getDestructor();
7166 if (Dtor) {
7167 StringRef ParentName =
7168 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7169 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7170 }
7171 }
7172
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007173 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007174 // implemented yet). Therefore we signal that GD was processed in this case.
7175 return true;
7176}
7177
7178bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7179 auto *VD = GD.getDecl();
7180 if (isa<FunctionDecl>(VD))
7181 return emitTargetFunctions(GD);
7182
7183 return emitTargetGlobalVariable(GD);
7184}
7185
7186llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7187 // If we have offloading in the current module, we need to emit the entries
7188 // now and register the offloading descriptor.
7189 createOffloadEntriesAndInfoMetadata();
7190
7191 // Create and register the offloading binary descriptors. This is the main
7192 // entity that captures all the information about offloading in the current
7193 // compilation unit.
7194 return createOffloadingBinaryDescriptorRegistration();
7195}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007196
7197void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7198 const OMPExecutableDirective &D,
7199 SourceLocation Loc,
7200 llvm::Value *OutlinedFn,
7201 ArrayRef<llvm::Value *> CapturedVars) {
7202 if (!CGF.HaveInsertPoint())
7203 return;
7204
7205 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7206 CodeGenFunction::RunCleanupsScope Scope(CGF);
7207
7208 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7209 llvm::Value *Args[] = {
7210 RTLoc,
7211 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7212 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7213 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7214 RealArgs.append(std::begin(Args), std::end(Args));
7215 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7216
7217 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7218 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7219}
7220
7221void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007222 const Expr *NumTeams,
7223 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007224 SourceLocation Loc) {
7225 if (!CGF.HaveInsertPoint())
7226 return;
7227
7228 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7229
Carlo Bertollic6872252016-04-04 15:55:02 +00007230 llvm::Value *NumTeamsVal =
7231 (NumTeams)
7232 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7233 CGF.CGM.Int32Ty, /* isSigned = */ true)
7234 : CGF.Builder.getInt32(0);
7235
7236 llvm::Value *ThreadLimitVal =
7237 (ThreadLimit)
7238 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7239 CGF.CGM.Int32Ty, /* isSigned = */ true)
7240 : CGF.Builder.getInt32(0);
7241
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007242 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007243 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7244 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007245 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7246 PushNumTeamsArgs);
7247}
Samuel Antaodf158d52016-04-27 22:58:19 +00007248
Samuel Antaocc10b852016-07-28 14:23:26 +00007249void CGOpenMPRuntime::emitTargetDataCalls(
7250 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7251 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007252 if (!CGF.HaveInsertPoint())
7253 return;
7254
Samuel Antaocc10b852016-07-28 14:23:26 +00007255 // Action used to replace the default codegen action and turn privatization
7256 // off.
7257 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007258
7259 // Generate the code for the opening of the data environment. Capture all the
7260 // arguments of the runtime call by reference because they are used in the
7261 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007262 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7263 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007264 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007265 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007266 MappableExprsHandler::MapValuesArrayTy Pointers;
7267 MappableExprsHandler::MapValuesArrayTy Sizes;
7268 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7269
7270 // Get map clause information.
7271 MappableExprsHandler MCHandler(D, CGF);
7272 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007273
7274 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007275 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007276
7277 llvm::Value *BasePointersArrayArg = nullptr;
7278 llvm::Value *PointersArrayArg = nullptr;
7279 llvm::Value *SizesArrayArg = nullptr;
7280 llvm::Value *MapTypesArrayArg = nullptr;
7281 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007282 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007283
7284 // Emit device ID if any.
7285 llvm::Value *DeviceID = nullptr;
7286 if (Device)
7287 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7288 CGF.Int32Ty, /*isSigned=*/true);
7289 else
7290 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7291
7292 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007293 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007294
7295 llvm::Value *OffloadingArgs[] = {
7296 DeviceID, PointerNum, BasePointersArrayArg,
7297 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7298 auto &RT = CGF.CGM.getOpenMPRuntime();
7299 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7300 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007301
7302 // If device pointer privatization is required, emit the body of the region
7303 // here. It will have to be duplicated: with and without privatization.
7304 if (!Info.CaptureDeviceAddrMap.empty())
7305 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007306 };
7307
7308 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007309 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007310 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007311
7312 llvm::Value *BasePointersArrayArg = nullptr;
7313 llvm::Value *PointersArrayArg = nullptr;
7314 llvm::Value *SizesArrayArg = nullptr;
7315 llvm::Value *MapTypesArrayArg = nullptr;
7316 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007317 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007318
7319 // Emit device ID if any.
7320 llvm::Value *DeviceID = nullptr;
7321 if (Device)
7322 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7323 CGF.Int32Ty, /*isSigned=*/true);
7324 else
7325 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7326
7327 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007328 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007329
7330 llvm::Value *OffloadingArgs[] = {
7331 DeviceID, PointerNum, BasePointersArrayArg,
7332 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7333 auto &RT = CGF.CGM.getOpenMPRuntime();
7334 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7335 OffloadingArgs);
7336 };
7337
Samuel Antaocc10b852016-07-28 14:23:26 +00007338 // If we need device pointer privatization, we need to emit the body of the
7339 // region with no privatization in the 'else' branch of the conditional.
7340 // Otherwise, we don't have to do anything.
7341 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7342 PrePostActionTy &) {
7343 if (!Info.CaptureDeviceAddrMap.empty()) {
7344 CodeGen.setAction(NoPrivAction);
7345 CodeGen(CGF);
7346 }
7347 };
7348
7349 // We don't have to do anything to close the region if the if clause evaluates
7350 // to false.
7351 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007352
7353 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007354 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007355 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007356 RegionCodeGenTy RCG(BeginThenGen);
7357 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007358 }
7359
Samuel Antaocc10b852016-07-28 14:23:26 +00007360 // If we don't require privatization of device pointers, we emit the body in
7361 // between the runtime calls. This avoids duplicating the body code.
7362 if (Info.CaptureDeviceAddrMap.empty()) {
7363 CodeGen.setAction(NoPrivAction);
7364 CodeGen(CGF);
7365 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007366
7367 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007368 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007369 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007370 RegionCodeGenTy RCG(EndThenGen);
7371 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007372 }
7373}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007374
Samuel Antao8d2d7302016-05-26 18:30:22 +00007375void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007376 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7377 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007378 if (!CGF.HaveInsertPoint())
7379 return;
7380
Samuel Antao8dd66282016-04-27 23:14:30 +00007381 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007382 isa<OMPTargetExitDataDirective>(D) ||
7383 isa<OMPTargetUpdateDirective>(D)) &&
7384 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007385
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007386 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007387 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007388 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007389 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007390 MappableExprsHandler::MapValuesArrayTy Pointers;
7391 MappableExprsHandler::MapValuesArrayTy Sizes;
7392 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7393
7394 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007395 MappableExprsHandler MEHandler(D, CGF);
7396 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007397
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007398 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007399 TargetDataInfo Info;
7400 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7401 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7402 Info.PointersArray, Info.SizesArray,
7403 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007404
7405 // Emit device ID if any.
7406 llvm::Value *DeviceID = nullptr;
7407 if (Device)
7408 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7409 CGF.Int32Ty, /*isSigned=*/true);
7410 else
7411 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7412
7413 // Emit the number of elements in the offloading arrays.
7414 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7415
7416 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007417 DeviceID, PointerNum, Info.BasePointersArray,
7418 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007419
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007420 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007421 // Select the right runtime function call for each expected standalone
7422 // directive.
7423 OpenMPRTLFunction RTLFn;
7424 switch (D.getDirectiveKind()) {
7425 default:
7426 llvm_unreachable("Unexpected standalone target data directive.");
7427 break;
7428 case OMPD_target_enter_data:
7429 RTLFn = OMPRTL__tgt_target_data_begin;
7430 break;
7431 case OMPD_target_exit_data:
7432 RTLFn = OMPRTL__tgt_target_data_end;
7433 break;
7434 case OMPD_target_update:
7435 RTLFn = OMPRTL__tgt_target_data_update;
7436 break;
7437 }
7438 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007439 };
7440
7441 // In the event we get an if clause, we don't have to take any action on the
7442 // else side.
7443 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7444
7445 if (IfCond) {
7446 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7447 } else {
7448 RegionCodeGenTy ThenGenRCG(ThenGen);
7449 ThenGenRCG(CGF);
7450 }
7451}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007452
7453namespace {
7454 /// Kind of parameter in a function with 'declare simd' directive.
7455 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7456 /// Attribute set of the parameter.
7457 struct ParamAttrTy {
7458 ParamKindTy Kind = Vector;
7459 llvm::APSInt StrideOrArg;
7460 llvm::APSInt Alignment;
7461 };
7462} // namespace
7463
7464static unsigned evaluateCDTSize(const FunctionDecl *FD,
7465 ArrayRef<ParamAttrTy> ParamAttrs) {
7466 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7467 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7468 // of that clause. The VLEN value must be power of 2.
7469 // In other case the notion of the function`s "characteristic data type" (CDT)
7470 // is used to compute the vector length.
7471 // CDT is defined in the following order:
7472 // a) For non-void function, the CDT is the return type.
7473 // b) If the function has any non-uniform, non-linear parameters, then the
7474 // CDT is the type of the first such parameter.
7475 // c) If the CDT determined by a) or b) above is struct, union, or class
7476 // type which is pass-by-value (except for the type that maps to the
7477 // built-in complex data type), the characteristic data type is int.
7478 // d) If none of the above three cases is applicable, the CDT is int.
7479 // The VLEN is then determined based on the CDT and the size of vector
7480 // register of that ISA for which current vector version is generated. The
7481 // VLEN is computed using the formula below:
7482 // VLEN = sizeof(vector_register) / sizeof(CDT),
7483 // where vector register size specified in section 3.2.1 Registers and the
7484 // Stack Frame of original AMD64 ABI document.
7485 QualType RetType = FD->getReturnType();
7486 if (RetType.isNull())
7487 return 0;
7488 ASTContext &C = FD->getASTContext();
7489 QualType CDT;
7490 if (!RetType.isNull() && !RetType->isVoidType())
7491 CDT = RetType;
7492 else {
7493 unsigned Offset = 0;
7494 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7495 if (ParamAttrs[Offset].Kind == Vector)
7496 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7497 ++Offset;
7498 }
7499 if (CDT.isNull()) {
7500 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7501 if (ParamAttrs[I + Offset].Kind == Vector) {
7502 CDT = FD->getParamDecl(I)->getType();
7503 break;
7504 }
7505 }
7506 }
7507 }
7508 if (CDT.isNull())
7509 CDT = C.IntTy;
7510 CDT = CDT->getCanonicalTypeUnqualified();
7511 if (CDT->isRecordType() || CDT->isUnionType())
7512 CDT = C.IntTy;
7513 return C.getTypeSize(CDT);
7514}
7515
7516static void
7517emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007518 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007519 ArrayRef<ParamAttrTy> ParamAttrs,
7520 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7521 struct ISADataTy {
7522 char ISA;
7523 unsigned VecRegSize;
7524 };
7525 ISADataTy ISAData[] = {
7526 {
7527 'b', 128
7528 }, // SSE
7529 {
7530 'c', 256
7531 }, // AVX
7532 {
7533 'd', 256
7534 }, // AVX2
7535 {
7536 'e', 512
7537 }, // AVX512
7538 };
7539 llvm::SmallVector<char, 2> Masked;
7540 switch (State) {
7541 case OMPDeclareSimdDeclAttr::BS_Undefined:
7542 Masked.push_back('N');
7543 Masked.push_back('M');
7544 break;
7545 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7546 Masked.push_back('N');
7547 break;
7548 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7549 Masked.push_back('M');
7550 break;
7551 }
7552 for (auto Mask : Masked) {
7553 for (auto &Data : ISAData) {
7554 SmallString<256> Buffer;
7555 llvm::raw_svector_ostream Out(Buffer);
7556 Out << "_ZGV" << Data.ISA << Mask;
7557 if (!VLENVal) {
7558 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7559 evaluateCDTSize(FD, ParamAttrs));
7560 } else
7561 Out << VLENVal;
7562 for (auto &ParamAttr : ParamAttrs) {
7563 switch (ParamAttr.Kind){
7564 case LinearWithVarStride:
7565 Out << 's' << ParamAttr.StrideOrArg;
7566 break;
7567 case Linear:
7568 Out << 'l';
7569 if (!!ParamAttr.StrideOrArg)
7570 Out << ParamAttr.StrideOrArg;
7571 break;
7572 case Uniform:
7573 Out << 'u';
7574 break;
7575 case Vector:
7576 Out << 'v';
7577 break;
7578 }
7579 if (!!ParamAttr.Alignment)
7580 Out << 'a' << ParamAttr.Alignment;
7581 }
7582 Out << '_' << Fn->getName();
7583 Fn->addFnAttr(Out.str());
7584 }
7585 }
7586}
7587
7588void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7589 llvm::Function *Fn) {
7590 ASTContext &C = CGM.getContext();
7591 FD = FD->getCanonicalDecl();
7592 // Map params to their positions in function decl.
7593 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7594 if (isa<CXXMethodDecl>(FD))
7595 ParamPositions.insert({FD, 0});
7596 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007597 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007598 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7599 ++ParamPos;
7600 }
7601 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7602 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7603 // Mark uniform parameters.
7604 for (auto *E : Attr->uniforms()) {
7605 E = E->IgnoreParenImpCasts();
7606 unsigned Pos;
7607 if (isa<CXXThisExpr>(E))
7608 Pos = ParamPositions[FD];
7609 else {
7610 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7611 ->getCanonicalDecl();
7612 Pos = ParamPositions[PVD];
7613 }
7614 ParamAttrs[Pos].Kind = Uniform;
7615 }
7616 // Get alignment info.
7617 auto NI = Attr->alignments_begin();
7618 for (auto *E : Attr->aligneds()) {
7619 E = E->IgnoreParenImpCasts();
7620 unsigned Pos;
7621 QualType ParmTy;
7622 if (isa<CXXThisExpr>(E)) {
7623 Pos = ParamPositions[FD];
7624 ParmTy = E->getType();
7625 } else {
7626 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7627 ->getCanonicalDecl();
7628 Pos = ParamPositions[PVD];
7629 ParmTy = PVD->getType();
7630 }
7631 ParamAttrs[Pos].Alignment =
7632 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7633 : llvm::APSInt::getUnsigned(
7634 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7635 .getQuantity());
7636 ++NI;
7637 }
7638 // Mark linear parameters.
7639 auto SI = Attr->steps_begin();
7640 auto MI = Attr->modifiers_begin();
7641 for (auto *E : Attr->linears()) {
7642 E = E->IgnoreParenImpCasts();
7643 unsigned Pos;
7644 if (isa<CXXThisExpr>(E))
7645 Pos = ParamPositions[FD];
7646 else {
7647 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7648 ->getCanonicalDecl();
7649 Pos = ParamPositions[PVD];
7650 }
7651 auto &ParamAttr = ParamAttrs[Pos];
7652 ParamAttr.Kind = Linear;
7653 if (*SI) {
7654 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7655 Expr::SE_AllowSideEffects)) {
7656 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7657 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7658 ParamAttr.Kind = LinearWithVarStride;
7659 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7660 ParamPositions[StridePVD->getCanonicalDecl()]);
7661 }
7662 }
7663 }
7664 }
7665 ++SI;
7666 ++MI;
7667 }
7668 llvm::APSInt VLENVal;
7669 if (const Expr *VLEN = Attr->getSimdlen())
7670 VLENVal = VLEN->EvaluateKnownConstInt(C);
7671 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7672 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7673 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7674 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7675 }
7676}
Alexey Bataev8b427062016-05-25 12:36:08 +00007677
7678namespace {
7679/// Cleanup action for doacross support.
7680class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7681public:
7682 static const int DoacrossFinArgs = 2;
7683
7684private:
7685 llvm::Value *RTLFn;
7686 llvm::Value *Args[DoacrossFinArgs];
7687
7688public:
7689 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7690 : RTLFn(RTLFn) {
7691 assert(CallArgs.size() == DoacrossFinArgs);
7692 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7693 }
7694 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7695 if (!CGF.HaveInsertPoint())
7696 return;
7697 CGF.EmitRuntimeCall(RTLFn, Args);
7698 }
7699};
7700} // namespace
7701
7702void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7703 const OMPLoopDirective &D) {
7704 if (!CGF.HaveInsertPoint())
7705 return;
7706
7707 ASTContext &C = CGM.getContext();
7708 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7709 RecordDecl *RD;
7710 if (KmpDimTy.isNull()) {
7711 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7712 // kmp_int64 lo; // lower
7713 // kmp_int64 up; // upper
7714 // kmp_int64 st; // stride
7715 // };
7716 RD = C.buildImplicitRecord("kmp_dim");
7717 RD->startDefinition();
7718 addFieldToRecordDecl(C, RD, Int64Ty);
7719 addFieldToRecordDecl(C, RD, Int64Ty);
7720 addFieldToRecordDecl(C, RD, Int64Ty);
7721 RD->completeDefinition();
7722 KmpDimTy = C.getRecordType(RD);
7723 } else
7724 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7725
7726 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7727 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7728 enum { LowerFD = 0, UpperFD, StrideFD };
7729 // Fill dims with data.
7730 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7731 // dims.upper = num_iterations;
7732 LValue UpperLVal =
7733 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7734 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7735 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7736 Int64Ty, D.getNumIterations()->getExprLoc());
7737 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7738 // dims.stride = 1;
7739 LValue StrideLVal =
7740 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7741 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7742 StrideLVal);
7743
7744 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7745 // kmp_int32 num_dims, struct kmp_dim * dims);
7746 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7747 getThreadID(CGF, D.getLocStart()),
7748 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7749 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7750 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7751
7752 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7753 CGF.EmitRuntimeCall(RTLFn, Args);
7754 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7755 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7756 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7757 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7758 llvm::makeArrayRef(FiniArgs));
7759}
7760
7761void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7762 const OMPDependClause *C) {
7763 QualType Int64Ty =
7764 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7765 const Expr *CounterVal = C->getCounterValue();
7766 assert(CounterVal);
7767 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7768 CounterVal->getType(), Int64Ty,
7769 CounterVal->getExprLoc());
7770 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7771 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7772 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7773 getThreadID(CGF, C->getLocStart()),
7774 CntAddr.getPointer()};
7775 llvm::Value *RTLFn;
7776 if (C->getDependencyKind() == OMPC_DEPEND_source)
7777 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7778 else {
7779 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7780 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7781 }
7782 CGF.EmitRuntimeCall(RTLFn, Args);
7783}
7784
Alexey Bataev3c595a62017-08-14 15:01:03 +00007785void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7786 ArrayRef<llvm::Value *> Args,
7787 SourceLocation Loc) const {
7788 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7789
7790 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007791 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007792 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007793 return;
7794 }
7795 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007796 CGF.EmitRuntimeCall(Callee, Args);
7797}
7798
7799void CGOpenMPRuntime::emitOutlinedFunctionCall(
7800 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7801 ArrayRef<llvm::Value *> Args) const {
7802 assert(Loc.isValid() && "Outlined function call location must be valid.");
7803 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007804}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007805
7806Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7807 const VarDecl *NativeParam,
7808 const VarDecl *TargetParam) const {
7809 return CGF.GetAddrOfLocalVar(NativeParam);
7810}