blob: ab1f64824a3aef4fa9307b4c59c528f9979555a7 [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) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000865 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000866}
867
868LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
869 const Expr *E) {
870 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
871 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
872 return LValue();
873}
874
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000875void ReductionCodeGen::emitAggregateInitialization(
876 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
877 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000878 // Emit VarDecl with copy init for arrays.
879 // Get the address of the original variable captured in current
880 // captured region.
881 auto *PrivateVD =
882 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000883 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
884 DRD ? ClausesData[N].ReductionOp : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000885 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000886}
887
888ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
889 ArrayRef<const Expr *> Privates,
890 ArrayRef<const Expr *> ReductionOps) {
891 ClausesData.reserve(Shareds.size());
892 SharedAddresses.reserve(Shareds.size());
893 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000894 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000895 auto IPriv = Privates.begin();
896 auto IRed = ReductionOps.begin();
897 for (const auto *Ref : Shareds) {
898 ClausesData.emplace_back(Ref, *IPriv, *IRed);
899 std::advance(IPriv, 1);
900 std::advance(IRed, 1);
901 }
902}
903
904void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
905 assert(SharedAddresses.size() == N &&
906 "Number of generated lvalues must be exactly N.");
907 SharedAddresses.emplace_back(emitSharedLValue(CGF, ClausesData[N].Ref),
908 emitSharedLValueUB(CGF, ClausesData[N].Ref));
909}
910
911void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
912 auto *PrivateVD =
913 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
914 QualType PrivateType = PrivateVD->getType();
915 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
916 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000917 Sizes.emplace_back(
918 CGF.getTypeSize(
919 SharedAddresses[N].first.getType().getNonReferenceType()),
920 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000921 return;
922 }
923 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000924 llvm::Value *SizeInChars;
925 llvm::Type *ElemType =
926 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
927 ->getElementType();
928 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000929 if (AsArraySection) {
930 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
931 SharedAddresses[N].first.getPointer());
932 Size = CGF.Builder.CreateNUWAdd(
933 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000934 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000935 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000936 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000937 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000938 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000939 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000940 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000941 CodeGenFunction::OpaqueValueMapping OpaqueMap(
942 CGF,
943 cast<OpaqueValueExpr>(
944 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
945 RValue::get(Size));
946 CGF.EmitVariablyModifiedType(PrivateType);
947}
948
949void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
950 llvm::Value *Size) {
951 auto *PrivateVD =
952 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
953 QualType PrivateType = PrivateVD->getType();
954 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
955 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000956 assert(!Size && !Sizes[N].second &&
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000957 "Size should be nullptr for non-variably modified redution "
958 "items.");
959 return;
960 }
961 CodeGenFunction::OpaqueValueMapping OpaqueMap(
962 CGF,
963 cast<OpaqueValueExpr>(
964 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
965 RValue::get(Size));
966 CGF.EmitVariablyModifiedType(PrivateType);
967}
968
969void ReductionCodeGen::emitInitialization(
970 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
971 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
972 assert(SharedAddresses.size() > N && "No variable was generated");
973 auto *PrivateVD =
974 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
975 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
976 QualType PrivateType = PrivateVD->getType();
977 PrivateAddr = CGF.Builder.CreateElementBitCast(
978 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
979 QualType SharedType = SharedAddresses[N].first.getType();
980 SharedLVal = CGF.MakeAddrLValue(
981 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
982 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +0000983 SharedType, SharedAddresses[N].first.getBaseInfo(),
984 CGF.CGM.getTBAAAccessInfo(SharedType));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000985 if (isa<OMPArraySectionExpr>(ClausesData[N].Ref) ||
986 CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000987 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000988 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
989 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
990 PrivateAddr, SharedLVal.getAddress(),
991 SharedLVal.getType());
992 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
993 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
994 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
995 PrivateVD->getType().getQualifiers(),
996 /*IsInitializer=*/false);
997 }
998}
999
1000bool ReductionCodeGen::needCleanups(unsigned N) {
1001 auto *PrivateVD =
1002 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1003 QualType PrivateType = PrivateVD->getType();
1004 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1005 return DTorKind != QualType::DK_none;
1006}
1007
1008void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1009 Address PrivateAddr) {
1010 auto *PrivateVD =
1011 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1012 QualType PrivateType = PrivateVD->getType();
1013 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1014 if (needCleanups(N)) {
1015 PrivateAddr = CGF.Builder.CreateElementBitCast(
1016 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1017 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1018 }
1019}
1020
1021static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1022 LValue BaseLV) {
1023 BaseTy = BaseTy.getNonReferenceType();
1024 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1025 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1026 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1027 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1028 else {
1029 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
1030 BaseTy->castAs<ReferenceType>());
1031 }
1032 BaseTy = BaseTy->getPointeeType();
1033 }
1034 return CGF.MakeAddrLValue(
1035 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1036 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001037 BaseLV.getType(), BaseLV.getBaseInfo(),
1038 CGF.CGM.getTBAAAccessInfo(BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001039}
1040
1041static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1042 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1043 llvm::Value *Addr) {
1044 Address Tmp = Address::invalid();
1045 Address TopTmp = Address::invalid();
1046 Address MostTopTmp = Address::invalid();
1047 BaseTy = BaseTy.getNonReferenceType();
1048 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1049 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1050 Tmp = CGF.CreateMemTemp(BaseTy);
1051 if (TopTmp.isValid())
1052 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1053 else
1054 MostTopTmp = Tmp;
1055 TopTmp = Tmp;
1056 BaseTy = BaseTy->getPointeeType();
1057 }
1058 llvm::Type *Ty = BaseLVType;
1059 if (Tmp.isValid())
1060 Ty = Tmp.getElementType();
1061 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1062 if (Tmp.isValid()) {
1063 CGF.Builder.CreateStore(Addr, Tmp);
1064 return MostTopTmp;
1065 }
1066 return Address(Addr, BaseLVAlignment);
1067}
1068
1069Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1070 Address PrivateAddr) {
1071 const DeclRefExpr *DE;
1072 const VarDecl *OrigVD = nullptr;
1073 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1074 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1075 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1076 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1077 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1078 Base = TempASE->getBase()->IgnoreParenImpCasts();
1079 DE = cast<DeclRefExpr>(Base);
1080 OrigVD = cast<VarDecl>(DE->getDecl());
1081 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1082 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1083 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1084 Base = TempASE->getBase()->IgnoreParenImpCasts();
1085 DE = cast<DeclRefExpr>(Base);
1086 OrigVD = cast<VarDecl>(DE->getDecl());
1087 }
1088 if (OrigVD) {
1089 BaseDecls.emplace_back(OrigVD);
1090 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1091 LValue BaseLValue =
1092 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1093 OriginalBaseLValue);
1094 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1095 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1096 llvm::Value *Ptr =
1097 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1098 return castToBase(CGF, OrigVD->getType(),
1099 SharedAddresses[N].first.getType(),
1100 OriginalBaseLValue.getPointer()->getType(),
1101 OriginalBaseLValue.getAlignment(), Ptr);
1102 }
1103 BaseDecls.emplace_back(
1104 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1105 return PrivateAddr;
1106}
1107
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001108bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1109 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1110 return DRD && DRD->getInitializer();
1111}
1112
Alexey Bataev18095712014-10-10 12:19:54 +00001113LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001114 return CGF.EmitLoadOfPointerLValue(
1115 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1116 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001117}
1118
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001119void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001120 if (!CGF.HaveInsertPoint())
1121 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001122 // 1.2.2 OpenMP Language Terminology
1123 // Structured block - An executable statement with a single entry at the
1124 // top and a single exit at the bottom.
1125 // The point of exit cannot be a branch out of the structured block.
1126 // longjmp() and throw() must not violate the entry/exit criteria.
1127 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001128 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001129 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001130}
1131
Alexey Bataev62b63b12015-03-10 07:28:44 +00001132LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1133 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001134 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1135 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001136 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001137}
1138
Alexey Bataev9959db52014-05-06 10:08:46 +00001139CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001140 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001141 IdentTy = llvm::StructType::create(
1142 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1143 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001144 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001145 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001146
1147 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001148}
1149
Alexey Bataev91797552015-03-18 04:13:55 +00001150void CGOpenMPRuntime::clear() {
1151 InternalVars.clear();
1152}
1153
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001154static llvm::Function *
1155emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1156 const Expr *CombinerInitializer, const VarDecl *In,
1157 const VarDecl *Out, bool IsCombiner) {
1158 // void .omp_combiner.(Ty *in, Ty *out);
1159 auto &C = CGM.getContext();
1160 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1161 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001162 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001163 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001164 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001165 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001166 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001167 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001168 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001169 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001170 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1171 auto *Fn = llvm::Function::Create(
1172 FnTy, llvm::GlobalValue::InternalLinkage,
1173 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1174 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001175 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001176 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001177 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001178 CodeGenFunction CGF(CGM);
1179 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1180 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1181 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1182 CodeGenFunction::OMPPrivateScope Scope(CGF);
1183 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1184 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1185 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1186 .getAddress();
1187 });
1188 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1189 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1190 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1191 .getAddress();
1192 });
1193 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001194 if (!IsCombiner && Out->hasInit() &&
1195 !CGF.isTrivialInitializer(Out->getInit())) {
1196 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1197 Out->getType().getQualifiers(),
1198 /*IsInitializer=*/true);
1199 }
1200 if (CombinerInitializer)
1201 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001202 Scope.ForceCleanup();
1203 CGF.FinishFunction();
1204 return Fn;
1205}
1206
1207void CGOpenMPRuntime::emitUserDefinedReduction(
1208 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1209 if (UDRMap.count(D) > 0)
1210 return;
1211 auto &C = CGM.getContext();
1212 if (!In || !Out) {
1213 In = &C.Idents.get("omp_in");
1214 Out = &C.Idents.get("omp_out");
1215 }
1216 llvm::Function *Combiner = emitCombinerOrInitializer(
1217 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1218 cast<VarDecl>(D->lookup(Out).front()),
1219 /*IsCombiner=*/true);
1220 llvm::Function *Initializer = nullptr;
1221 if (auto *Init = D->getInitializer()) {
1222 if (!Priv || !Orig) {
1223 Priv = &C.Idents.get("omp_priv");
1224 Orig = &C.Idents.get("omp_orig");
1225 }
1226 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001227 CGM, D->getType(),
1228 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1229 : nullptr,
1230 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001231 cast<VarDecl>(D->lookup(Priv).front()),
1232 /*IsCombiner=*/false);
1233 }
1234 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1235 if (CGF) {
1236 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1237 Decls.second.push_back(D);
1238 }
1239}
1240
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001241std::pair<llvm::Function *, llvm::Function *>
1242CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1243 auto I = UDRMap.find(D);
1244 if (I != UDRMap.end())
1245 return I->second;
1246 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1247 return UDRMap.lookup(D);
1248}
1249
John McCall7f416cc2015-09-08 08:05:57 +00001250// Layout information for ident_t.
1251static CharUnits getIdentAlign(CodeGenModule &CGM) {
1252 return CGM.getPointerAlign();
1253}
1254static CharUnits getIdentSize(CodeGenModule &CGM) {
1255 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1256 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1257}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001258static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001259 // All the fields except the last are i32, so this works beautifully.
1260 return unsigned(Field) * CharUnits::fromQuantity(4);
1261}
1262static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001263 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001264 const llvm::Twine &Name = "") {
1265 auto Offset = getOffsetOfIdentField(Field);
1266 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1267}
1268
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001269static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1270 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1271 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1272 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001273 assert(ThreadIDVar->getType()->isPointerType() &&
1274 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001275 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001276 bool HasCancel = false;
1277 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1278 HasCancel = OPD->hasCancel();
1279 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1280 HasCancel = OPSD->hasCancel();
1281 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1282 HasCancel = OPFD->hasCancel();
1283 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001284 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001285 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001286 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001287}
1288
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001289llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1290 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1291 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1292 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1293 return emitParallelOrTeamsOutlinedFunction(
1294 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1295}
1296
1297llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1298 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1299 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1300 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1301 return emitParallelOrTeamsOutlinedFunction(
1302 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1303}
1304
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001305llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1306 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001307 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1308 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1309 bool Tied, unsigned &NumberOfParts) {
1310 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1311 PrePostActionTy &) {
1312 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1313 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1314 llvm::Value *TaskArgs[] = {
1315 UpLoc, ThreadID,
1316 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1317 TaskTVar->getType()->castAs<PointerType>())
1318 .getPointer()};
1319 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1320 };
1321 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1322 UntiedCodeGen);
1323 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001324 assert(!ThreadIDVar->getType()->isPointerType() &&
1325 "thread id variable must be of type kmp_int32 for tasks");
1326 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001327 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001328 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001329 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1330 InnermostKind,
1331 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001332 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001333 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1334 if (!Tied)
1335 NumberOfParts = Action.getNumberOfParts();
1336 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001337}
1338
Alexey Bataev50b3c952016-02-19 10:38:26 +00001339Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001340 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001341 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001342 if (!Entry) {
1343 if (!DefaultOpenMPPSource) {
1344 // Initialize default location for psource field of ident_t structure of
1345 // all ident_t objects. Format is ";file;function;line;column;;".
1346 // Taken from
1347 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1348 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001349 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001350 DefaultOpenMPPSource =
1351 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1352 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001353
John McCall23c9dc62016-11-28 22:18:27 +00001354 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001355 auto fields = builder.beginStruct(IdentTy);
1356 fields.addInt(CGM.Int32Ty, 0);
1357 fields.addInt(CGM.Int32Ty, Flags);
1358 fields.addInt(CGM.Int32Ty, 0);
1359 fields.addInt(CGM.Int32Ty, 0);
1360 fields.add(DefaultOpenMPPSource);
1361 auto DefaultOpenMPLocation =
1362 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1363 llvm::GlobalValue::PrivateLinkage);
1364 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1365
John McCall7f416cc2015-09-08 08:05:57 +00001366 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001367 }
John McCall7f416cc2015-09-08 08:05:57 +00001368 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001369}
1370
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001371llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1372 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001373 unsigned Flags) {
1374 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001375 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001376 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001377 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001378 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001379
1380 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1381
John McCall7f416cc2015-09-08 08:05:57 +00001382 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001383 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1384 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001385 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1386
Alexander Musmanc6388682014-12-15 07:07:06 +00001387 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1388 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001389 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001390 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001391 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1392 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001393 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001394 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001395 LocValue = AI;
1396
1397 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1398 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001399 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001400 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001401 }
1402
1403 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001404 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001405
Alexey Bataevf002aca2014-05-30 05:48:40 +00001406 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1407 if (OMPDebugLoc == nullptr) {
1408 SmallString<128> Buffer2;
1409 llvm::raw_svector_ostream OS2(Buffer2);
1410 // Build debug location
1411 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1412 OS2 << ";" << PLoc.getFilename() << ";";
1413 if (const FunctionDecl *FD =
1414 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1415 OS2 << FD->getQualifiedNameAsString();
1416 }
1417 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1418 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1419 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001420 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001421 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001422 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1423
John McCall7f416cc2015-09-08 08:05:57 +00001424 // Our callers always pass this to a runtime function, so for
1425 // convenience, go ahead and return a naked pointer.
1426 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001427}
1428
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001429llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1430 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001431 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1432
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001433 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001434 // Check whether we've already cached a load of the thread id in this
1435 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001436 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001437 if (I != OpenMPLocThreadIDMap.end()) {
1438 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001439 if (ThreadID != nullptr)
1440 return ThreadID;
1441 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001442 // If exceptions are enabled, do not use parameter to avoid possible crash.
1443 if (!CGF.getInvokeDest()) {
1444 if (auto *OMPRegionInfo =
1445 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1446 if (OMPRegionInfo->getThreadIDVariable()) {
1447 // Check if this an outlined function with thread id passed as argument.
1448 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1449 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1450 // If value loaded in entry block, cache it and use it everywhere in
1451 // function.
1452 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1453 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1454 Elem.second.ThreadID = ThreadID;
1455 }
1456 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001457 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001458 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001459 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001460
1461 // This is not an outlined function region - need to call __kmpc_int32
1462 // kmpc_global_thread_num(ident_t *loc).
1463 // Generate thread id value and cache this value for use across the
1464 // function.
1465 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1466 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1467 ThreadID =
1468 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1469 emitUpdateLocation(CGF, Loc));
1470 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1471 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001472 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001473}
1474
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001475void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001476 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001477 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1478 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001479 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1480 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1481 UDRMap.erase(D);
1482 }
1483 FunctionUDRMap.erase(CGF.CurFn);
1484 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001485}
1486
1487llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001488 if (!IdentTy) {
1489 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001490 return llvm::PointerType::getUnqual(IdentTy);
1491}
1492
1493llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001494 if (!Kmpc_MicroTy) {
1495 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1496 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1497 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1498 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1499 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001500 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1501}
1502
1503llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001504CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001505 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001506 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001507 case OMPRTL__kmpc_fork_call: {
1508 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1509 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001510 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1511 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001512 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001513 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001514 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1515 break;
1516 }
1517 case OMPRTL__kmpc_global_thread_num: {
1518 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001519 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001520 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001521 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001522 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1523 break;
1524 }
Alexey Bataev97720002014-11-11 04:05:39 +00001525 case OMPRTL__kmpc_threadprivate_cached: {
1526 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1527 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1528 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1529 CGM.VoidPtrTy, CGM.SizeTy,
1530 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1531 llvm::FunctionType *FnTy =
1532 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1533 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1534 break;
1535 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001536 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001537 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1538 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001539 llvm::Type *TypeParams[] = {
1540 getIdentTyPointerTy(), CGM.Int32Ty,
1541 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1542 llvm::FunctionType *FnTy =
1543 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1544 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1545 break;
1546 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001547 case OMPRTL__kmpc_critical_with_hint: {
1548 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1549 // kmp_critical_name *crit, uintptr_t hint);
1550 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1551 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1552 CGM.IntPtrTy};
1553 llvm::FunctionType *FnTy =
1554 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1555 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1556 break;
1557 }
Alexey Bataev97720002014-11-11 04:05:39 +00001558 case OMPRTL__kmpc_threadprivate_register: {
1559 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1560 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1561 // typedef void *(*kmpc_ctor)(void *);
1562 auto KmpcCtorTy =
1563 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1564 /*isVarArg*/ false)->getPointerTo();
1565 // typedef void *(*kmpc_cctor)(void *, void *);
1566 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1567 auto KmpcCopyCtorTy =
1568 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1569 /*isVarArg*/ false)->getPointerTo();
1570 // typedef void (*kmpc_dtor)(void *);
1571 auto KmpcDtorTy =
1572 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1573 ->getPointerTo();
1574 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1575 KmpcCopyCtorTy, KmpcDtorTy};
1576 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1577 /*isVarArg*/ false);
1578 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1579 break;
1580 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001581 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001582 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1583 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001584 llvm::Type *TypeParams[] = {
1585 getIdentTyPointerTy(), CGM.Int32Ty,
1586 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1587 llvm::FunctionType *FnTy =
1588 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1589 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1590 break;
1591 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001592 case OMPRTL__kmpc_cancel_barrier: {
1593 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1594 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001595 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1596 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001597 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001599 break;
1600 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001601 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001602 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001603 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1604 llvm::FunctionType *FnTy =
1605 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1606 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1607 break;
1608 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001609 case OMPRTL__kmpc_for_static_fini: {
1610 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1611 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1612 llvm::FunctionType *FnTy =
1613 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1614 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1615 break;
1616 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001617 case OMPRTL__kmpc_push_num_threads: {
1618 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1619 // kmp_int32 num_threads)
1620 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1621 CGM.Int32Ty};
1622 llvm::FunctionType *FnTy =
1623 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1624 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1625 break;
1626 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001627 case OMPRTL__kmpc_serialized_parallel: {
1628 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1629 // global_tid);
1630 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1631 llvm::FunctionType *FnTy =
1632 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1633 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1634 break;
1635 }
1636 case OMPRTL__kmpc_end_serialized_parallel: {
1637 // Build void __kmpc_end_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_end_serialized_parallel");
1643 break;
1644 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001645 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001646 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001647 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1648 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001649 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001650 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1651 break;
1652 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001653 case OMPRTL__kmpc_master: {
1654 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1655 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1656 llvm::FunctionType *FnTy =
1657 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1658 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1659 break;
1660 }
1661 case OMPRTL__kmpc_end_master: {
1662 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1663 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1664 llvm::FunctionType *FnTy =
1665 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1666 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1667 break;
1668 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001669 case OMPRTL__kmpc_omp_taskyield: {
1670 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1671 // int end_part);
1672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1673 llvm::FunctionType *FnTy =
1674 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1675 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1676 break;
1677 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001678 case OMPRTL__kmpc_single: {
1679 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1680 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1681 llvm::FunctionType *FnTy =
1682 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1683 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1684 break;
1685 }
1686 case OMPRTL__kmpc_end_single: {
1687 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1688 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1689 llvm::FunctionType *FnTy =
1690 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1691 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1692 break;
1693 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001694 case OMPRTL__kmpc_omp_task_alloc: {
1695 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1696 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1697 // kmp_routine_entry_t *task_entry);
1698 assert(KmpRoutineEntryPtrTy != nullptr &&
1699 "Type kmp_routine_entry_t must be created.");
1700 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1701 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1702 // Return void * and then cast to particular kmp_task_t type.
1703 llvm::FunctionType *FnTy =
1704 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1705 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1706 break;
1707 }
1708 case OMPRTL__kmpc_omp_task: {
1709 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1710 // *new_task);
1711 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1712 CGM.VoidPtrTy};
1713 llvm::FunctionType *FnTy =
1714 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1715 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1716 break;
1717 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001718 case OMPRTL__kmpc_copyprivate: {
1719 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001720 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001721 // kmp_int32 didit);
1722 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1723 auto *CpyFnTy =
1724 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001725 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001726 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1727 CGM.Int32Ty};
1728 llvm::FunctionType *FnTy =
1729 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1730 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1731 break;
1732 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001733 case OMPRTL__kmpc_reduce: {
1734 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1735 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1736 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1737 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1738 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1739 /*isVarArg=*/false);
1740 llvm::Type *TypeParams[] = {
1741 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1742 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1743 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1744 llvm::FunctionType *FnTy =
1745 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1746 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1747 break;
1748 }
1749 case OMPRTL__kmpc_reduce_nowait: {
1750 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1751 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1752 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1753 // *lck);
1754 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1755 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1756 /*isVarArg=*/false);
1757 llvm::Type *TypeParams[] = {
1758 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1759 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1760 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1761 llvm::FunctionType *FnTy =
1762 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1763 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1764 break;
1765 }
1766 case OMPRTL__kmpc_end_reduce: {
1767 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1768 // kmp_critical_name *lck);
1769 llvm::Type *TypeParams[] = {
1770 getIdentTyPointerTy(), CGM.Int32Ty,
1771 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1772 llvm::FunctionType *FnTy =
1773 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1774 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1775 break;
1776 }
1777 case OMPRTL__kmpc_end_reduce_nowait: {
1778 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1779 // kmp_critical_name *lck);
1780 llvm::Type *TypeParams[] = {
1781 getIdentTyPointerTy(), CGM.Int32Ty,
1782 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1783 llvm::FunctionType *FnTy =
1784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1785 RTLFn =
1786 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1787 break;
1788 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001789 case OMPRTL__kmpc_omp_task_begin_if0: {
1790 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1791 // *new_task);
1792 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1793 CGM.VoidPtrTy};
1794 llvm::FunctionType *FnTy =
1795 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1796 RTLFn =
1797 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1798 break;
1799 }
1800 case OMPRTL__kmpc_omp_task_complete_if0: {
1801 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1802 // *new_task);
1803 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1804 CGM.VoidPtrTy};
1805 llvm::FunctionType *FnTy =
1806 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1807 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1808 /*Name=*/"__kmpc_omp_task_complete_if0");
1809 break;
1810 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001811 case OMPRTL__kmpc_ordered: {
1812 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1813 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1814 llvm::FunctionType *FnTy =
1815 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1816 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1817 break;
1818 }
1819 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001820 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001821 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1822 llvm::FunctionType *FnTy =
1823 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1824 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1825 break;
1826 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001827 case OMPRTL__kmpc_omp_taskwait: {
1828 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1829 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1830 llvm::FunctionType *FnTy =
1831 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1832 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1833 break;
1834 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001835 case OMPRTL__kmpc_taskgroup: {
1836 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1837 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1838 llvm::FunctionType *FnTy =
1839 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1840 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1841 break;
1842 }
1843 case OMPRTL__kmpc_end_taskgroup: {
1844 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1845 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1846 llvm::FunctionType *FnTy =
1847 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1848 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1849 break;
1850 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001851 case OMPRTL__kmpc_push_proc_bind: {
1852 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1853 // int proc_bind)
1854 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1855 llvm::FunctionType *FnTy =
1856 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1857 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1858 break;
1859 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001860 case OMPRTL__kmpc_omp_task_with_deps: {
1861 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1862 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1863 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1864 llvm::Type *TypeParams[] = {
1865 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1866 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1867 llvm::FunctionType *FnTy =
1868 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1869 RTLFn =
1870 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1871 break;
1872 }
1873 case OMPRTL__kmpc_omp_wait_deps: {
1874 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1875 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1876 // kmp_depend_info_t *noalias_dep_list);
1877 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1878 CGM.Int32Ty, CGM.VoidPtrTy,
1879 CGM.Int32Ty, CGM.VoidPtrTy};
1880 llvm::FunctionType *FnTy =
1881 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1882 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1883 break;
1884 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001885 case OMPRTL__kmpc_cancellationpoint: {
1886 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1887 // global_tid, kmp_int32 cncl_kind)
1888 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1889 llvm::FunctionType *FnTy =
1890 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1891 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1892 break;
1893 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001894 case OMPRTL__kmpc_cancel: {
1895 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1896 // 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_cancel");
1901 break;
1902 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001903 case OMPRTL__kmpc_push_num_teams: {
1904 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1905 // kmp_int32 num_teams, kmp_int32 num_threads)
1906 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1907 CGM.Int32Ty};
1908 llvm::FunctionType *FnTy =
1909 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1910 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1911 break;
1912 }
1913 case OMPRTL__kmpc_fork_teams: {
1914 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1915 // microtask, ...);
1916 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1917 getKmpc_MicroPointerTy()};
1918 llvm::FunctionType *FnTy =
1919 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1920 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1921 break;
1922 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001923 case OMPRTL__kmpc_taskloop: {
1924 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1925 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1926 // sched, kmp_uint64 grainsize, void *task_dup);
1927 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1928 CGM.IntTy,
1929 CGM.VoidPtrTy,
1930 CGM.IntTy,
1931 CGM.Int64Ty->getPointerTo(),
1932 CGM.Int64Ty->getPointerTo(),
1933 CGM.Int64Ty,
1934 CGM.IntTy,
1935 CGM.IntTy,
1936 CGM.Int64Ty,
1937 CGM.VoidPtrTy};
1938 llvm::FunctionType *FnTy =
1939 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1940 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1941 break;
1942 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001943 case OMPRTL__kmpc_doacross_init: {
1944 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1945 // num_dims, struct kmp_dim *dims);
1946 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1947 CGM.Int32Ty,
1948 CGM.Int32Ty,
1949 CGM.VoidPtrTy};
1950 llvm::FunctionType *FnTy =
1951 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1952 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1953 break;
1954 }
1955 case OMPRTL__kmpc_doacross_fini: {
1956 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1957 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1958 llvm::FunctionType *FnTy =
1959 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1960 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1961 break;
1962 }
1963 case OMPRTL__kmpc_doacross_post: {
1964 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1965 // *vec);
1966 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1967 CGM.Int64Ty->getPointerTo()};
1968 llvm::FunctionType *FnTy =
1969 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1970 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1971 break;
1972 }
1973 case OMPRTL__kmpc_doacross_wait: {
1974 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1975 // *vec);
1976 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1977 CGM.Int64Ty->getPointerTo()};
1978 llvm::FunctionType *FnTy =
1979 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1980 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1981 break;
1982 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001983 case OMPRTL__kmpc_task_reduction_init: {
1984 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1985 // *data);
1986 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
1987 llvm::FunctionType *FnTy =
1988 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1989 RTLFn =
1990 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
1991 break;
1992 }
1993 case OMPRTL__kmpc_task_reduction_get_th_data: {
1994 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
1995 // *d);
1996 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
1997 llvm::FunctionType *FnTy =
1998 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1999 RTLFn = CGM.CreateRuntimeFunction(
2000 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2001 break;
2002 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002003 case OMPRTL__tgt_target: {
2004 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
2005 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
2006 // *arg_types);
2007 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2008 CGM.VoidPtrTy,
2009 CGM.Int32Ty,
2010 CGM.VoidPtrPtrTy,
2011 CGM.VoidPtrPtrTy,
2012 CGM.SizeTy->getPointerTo(),
2013 CGM.Int32Ty->getPointerTo()};
2014 llvm::FunctionType *FnTy =
2015 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2016 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2017 break;
2018 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002019 case OMPRTL__tgt_target_teams: {
2020 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2021 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2022 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2023 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2024 CGM.VoidPtrTy,
2025 CGM.Int32Ty,
2026 CGM.VoidPtrPtrTy,
2027 CGM.VoidPtrPtrTy,
2028 CGM.SizeTy->getPointerTo(),
2029 CGM.Int32Ty->getPointerTo(),
2030 CGM.Int32Ty,
2031 CGM.Int32Ty};
2032 llvm::FunctionType *FnTy =
2033 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2034 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2035 break;
2036 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002037 case OMPRTL__tgt_register_lib: {
2038 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2039 QualType ParamTy =
2040 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2041 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2042 llvm::FunctionType *FnTy =
2043 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2044 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2045 break;
2046 }
2047 case OMPRTL__tgt_unregister_lib: {
2048 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2049 QualType ParamTy =
2050 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2051 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2052 llvm::FunctionType *FnTy =
2053 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2054 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2055 break;
2056 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002057 case OMPRTL__tgt_target_data_begin: {
2058 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2059 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2060 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2061 CGM.Int32Ty,
2062 CGM.VoidPtrPtrTy,
2063 CGM.VoidPtrPtrTy,
2064 CGM.SizeTy->getPointerTo(),
2065 CGM.Int32Ty->getPointerTo()};
2066 llvm::FunctionType *FnTy =
2067 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2068 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2069 break;
2070 }
2071 case OMPRTL__tgt_target_data_end: {
2072 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2073 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2074 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2075 CGM.Int32Ty,
2076 CGM.VoidPtrPtrTy,
2077 CGM.VoidPtrPtrTy,
2078 CGM.SizeTy->getPointerTo(),
2079 CGM.Int32Ty->getPointerTo()};
2080 llvm::FunctionType *FnTy =
2081 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2082 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2083 break;
2084 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002085 case OMPRTL__tgt_target_data_update: {
2086 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2087 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2088 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2089 CGM.Int32Ty,
2090 CGM.VoidPtrPtrTy,
2091 CGM.VoidPtrPtrTy,
2092 CGM.SizeTy->getPointerTo(),
2093 CGM.Int32Ty->getPointerTo()};
2094 llvm::FunctionType *FnTy =
2095 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2096 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2097 break;
2098 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002099 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002100 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002101 return RTLFn;
2102}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002103
Alexander Musman21212e42015-03-13 10:38:23 +00002104llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2105 bool IVSigned) {
2106 assert((IVSize == 32 || IVSize == 64) &&
2107 "IV size is not compatible with the omp runtime");
2108 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2109 : "__kmpc_for_static_init_4u")
2110 : (IVSigned ? "__kmpc_for_static_init_8"
2111 : "__kmpc_for_static_init_8u");
2112 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2113 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2114 llvm::Type *TypeParams[] = {
2115 getIdentTyPointerTy(), // loc
2116 CGM.Int32Ty, // tid
2117 CGM.Int32Ty, // schedtype
2118 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2119 PtrTy, // p_lower
2120 PtrTy, // p_upper
2121 PtrTy, // p_stride
2122 ITy, // incr
2123 ITy // chunk
2124 };
2125 llvm::FunctionType *FnTy =
2126 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2127 return CGM.CreateRuntimeFunction(FnTy, Name);
2128}
2129
Alexander Musman92bdaab2015-03-12 13:37:50 +00002130llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2131 bool IVSigned) {
2132 assert((IVSize == 32 || IVSize == 64) &&
2133 "IV size is not compatible with the omp runtime");
2134 auto Name =
2135 IVSize == 32
2136 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2137 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2138 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2139 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2140 CGM.Int32Ty, // tid
2141 CGM.Int32Ty, // schedtype
2142 ITy, // lower
2143 ITy, // upper
2144 ITy, // stride
2145 ITy // chunk
2146 };
2147 llvm::FunctionType *FnTy =
2148 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2149 return CGM.CreateRuntimeFunction(FnTy, Name);
2150}
2151
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002152llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2153 bool IVSigned) {
2154 assert((IVSize == 32 || IVSize == 64) &&
2155 "IV size is not compatible with the omp runtime");
2156 auto Name =
2157 IVSize == 32
2158 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2159 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2160 llvm::Type *TypeParams[] = {
2161 getIdentTyPointerTy(), // loc
2162 CGM.Int32Ty, // tid
2163 };
2164 llvm::FunctionType *FnTy =
2165 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2166 return CGM.CreateRuntimeFunction(FnTy, Name);
2167}
2168
Alexander Musman92bdaab2015-03-12 13:37:50 +00002169llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2170 bool IVSigned) {
2171 assert((IVSize == 32 || IVSize == 64) &&
2172 "IV size is not compatible with the omp runtime");
2173 auto Name =
2174 IVSize == 32
2175 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2176 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2177 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2178 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2179 llvm::Type *TypeParams[] = {
2180 getIdentTyPointerTy(), // loc
2181 CGM.Int32Ty, // tid
2182 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2183 PtrTy, // p_lower
2184 PtrTy, // p_upper
2185 PtrTy // p_stride
2186 };
2187 llvm::FunctionType *FnTy =
2188 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2189 return CGM.CreateRuntimeFunction(FnTy, Name);
2190}
2191
Alexey Bataev97720002014-11-11 04:05:39 +00002192llvm::Constant *
2193CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002194 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2195 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002196 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002197 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002198 Twine(CGM.getMangledName(VD)) + ".cache.");
2199}
2200
John McCall7f416cc2015-09-08 08:05:57 +00002201Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2202 const VarDecl *VD,
2203 Address VDAddr,
2204 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002205 if (CGM.getLangOpts().OpenMPUseTLS &&
2206 CGM.getContext().getTargetInfo().isTLSSupported())
2207 return VDAddr;
2208
John McCall7f416cc2015-09-08 08:05:57 +00002209 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002210 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002211 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2212 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002213 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2214 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002215 return Address(CGF.EmitRuntimeCall(
2216 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2217 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002218}
2219
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002220void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002221 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002222 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2223 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2224 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002225 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2226 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002227 OMPLoc);
2228 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2229 // to register constructor/destructor for variable.
2230 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002231 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2232 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002233 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002234 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002235 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002236}
2237
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002238llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002239 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002240 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002241 if (CGM.getLangOpts().OpenMPUseTLS &&
2242 CGM.getContext().getTargetInfo().isTLSSupported())
2243 return nullptr;
2244
Alexey Bataev97720002014-11-11 04:05:39 +00002245 VD = VD->getDefinition(CGM.getContext());
2246 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2247 ThreadPrivateWithDefinition.insert(VD);
2248 QualType ASTTy = VD->getType();
2249
2250 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2251 auto Init = VD->getAnyInitializer();
2252 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2253 // Generate function that re-emits the declaration's initializer into the
2254 // threadprivate copy of the variable VD
2255 CodeGenFunction CtorCGF(CGM);
2256 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002257 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2258 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002259 Args.push_back(&Dst);
2260
John McCallc56a8b32016-03-11 04:30:31 +00002261 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2262 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002263 auto FTy = CGM.getTypes().GetFunctionType(FI);
2264 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002265 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002266 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2267 Args, SourceLocation());
2268 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002269 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002270 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002271 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2272 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2273 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002274 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2275 /*IsInitializer=*/true);
2276 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002277 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002278 CGM.getContext().VoidPtrTy, Dst.getLocation());
2279 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2280 CtorCGF.FinishFunction();
2281 Ctor = Fn;
2282 }
2283 if (VD->getType().isDestructedType() != QualType::DK_none) {
2284 // Generate function that emits destructor call for the threadprivate copy
2285 // of the variable VD
2286 CodeGenFunction DtorCGF(CGM);
2287 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002288 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2289 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002290 Args.push_back(&Dst);
2291
John McCallc56a8b32016-03-11 04:30:31 +00002292 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2293 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002294 auto FTy = CGM.getTypes().GetFunctionType(FI);
2295 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002296 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002297 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002298 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2299 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002300 // Create a scope with an artificial location for the body of this function.
2301 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002302 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2303 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002304 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2305 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002306 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2307 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2308 DtorCGF.FinishFunction();
2309 Dtor = Fn;
2310 }
2311 // Do not emit init function if it is not required.
2312 if (!Ctor && !Dtor)
2313 return nullptr;
2314
2315 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2316 auto CopyCtorTy =
2317 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2318 /*isVarArg=*/false)->getPointerTo();
2319 // Copying constructor for the threadprivate variable.
2320 // Must be NULL - reserved by runtime, but currently it requires that this
2321 // parameter is always NULL. Otherwise it fires assertion.
2322 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2323 if (Ctor == nullptr) {
2324 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2325 /*isVarArg=*/false)->getPointerTo();
2326 Ctor = llvm::Constant::getNullValue(CtorTy);
2327 }
2328 if (Dtor == nullptr) {
2329 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2330 /*isVarArg=*/false)->getPointerTo();
2331 Dtor = llvm::Constant::getNullValue(DtorTy);
2332 }
2333 if (!CGF) {
2334 auto InitFunctionTy =
2335 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2336 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002337 InitFunctionTy, ".__omp_threadprivate_init_.",
2338 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002339 CodeGenFunction InitCGF(CGM);
2340 FunctionArgList ArgList;
2341 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2342 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2343 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002344 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002345 InitCGF.FinishFunction();
2346 return InitFunction;
2347 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002348 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002349 }
2350 return nullptr;
2351}
2352
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002353Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2354 QualType VarType,
2355 StringRef Name) {
2356 llvm::Twine VarName(Name, ".artificial.");
2357 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2358 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2359 llvm::Value *Args[] = {
2360 emitUpdateLocation(CGF, SourceLocation()),
2361 getThreadID(CGF, SourceLocation()),
2362 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2363 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2364 /*IsSigned=*/false),
2365 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2366 return Address(
2367 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2368 CGF.EmitRuntimeCall(
2369 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2370 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2371 CGM.getPointerAlign());
2372}
2373
Alexey Bataev1d677132015-04-22 13:57:31 +00002374/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2375/// function. Here is the logic:
2376/// if (Cond) {
2377/// ThenGen();
2378/// } else {
2379/// ElseGen();
2380/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002381void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2382 const RegionCodeGenTy &ThenGen,
2383 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002384 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2385
2386 // If the condition constant folds and can be elided, try to avoid emitting
2387 // the condition and the dead arm of the if/else.
2388 bool CondConstant;
2389 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002390 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002391 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002392 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002393 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002394 return;
2395 }
2396
2397 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2398 // emit the conditional branch.
2399 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2400 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2401 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2402 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2403
2404 // Emit the 'then' code.
2405 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002406 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002407 CGF.EmitBranch(ContBlock);
2408 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002409 // There is no need to emit line number for unconditional branch.
2410 (void)ApplyDebugLocation::CreateEmpty(CGF);
2411 CGF.EmitBlock(ElseBlock);
2412 ElseGen(CGF);
2413 // There is no need to emit line number for unconditional branch.
2414 (void)ApplyDebugLocation::CreateEmpty(CGF);
2415 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002416 // Emit the continuation block for code after the if.
2417 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002418}
2419
Alexey Bataev1d677132015-04-22 13:57:31 +00002420void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2421 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002422 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002423 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002424 if (!CGF.HaveInsertPoint())
2425 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002426 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002427 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2428 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002429 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002430 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002431 llvm::Value *Args[] = {
2432 RTLoc,
2433 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002434 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002435 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2436 RealArgs.append(std::begin(Args), std::end(Args));
2437 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2438
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002439 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002440 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2441 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002442 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2443 PrePostActionTy &) {
2444 auto &RT = CGF.CGM.getOpenMPRuntime();
2445 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002446 // Build calls:
2447 // __kmpc_serialized_parallel(&Loc, GTid);
2448 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002449 CGF.EmitRuntimeCall(
2450 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002451
Alexey Bataev1d677132015-04-22 13:57:31 +00002452 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002453 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002454 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002455 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2456 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002457 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002458 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2459 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2460 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2461 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002462 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002463
Alexey Bataev1d677132015-04-22 13:57:31 +00002464 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002465 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002466 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002467 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2468 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002469 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002470 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002471 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002472 else {
2473 RegionCodeGenTy ThenRCG(ThenGen);
2474 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002475 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002476}
2477
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002478// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002479// thread-ID variable (it is passed in a first argument of the outlined function
2480// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2481// regular serial code region, get thread ID by calling kmp_int32
2482// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2483// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002484Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2485 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002486 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002487 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002488 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002489 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002490
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002491 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002492 auto Int32Ty =
2493 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2494 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2495 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002496 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002497
2498 return ThreadIDTemp;
2499}
2500
Alexey Bataev97720002014-11-11 04:05:39 +00002501llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002502CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002503 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002504 SmallString<256> Buffer;
2505 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002506 Out << Name;
2507 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002508 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2509 if (Elem.second) {
2510 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002511 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002512 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002513 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002514
David Blaikie13156b62014-11-19 03:06:06 +00002515 return Elem.second = new llvm::GlobalVariable(
2516 CGM.getModule(), Ty, /*IsConstant*/ false,
2517 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2518 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002519}
2520
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002521llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002522 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002523 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002524}
2525
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002526namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002527/// Common pre(post)-action for different OpenMP constructs.
2528class CommonActionTy final : public PrePostActionTy {
2529 llvm::Value *EnterCallee;
2530 ArrayRef<llvm::Value *> EnterArgs;
2531 llvm::Value *ExitCallee;
2532 ArrayRef<llvm::Value *> ExitArgs;
2533 bool Conditional;
2534 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002535
2536public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002537 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2538 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2539 bool Conditional = false)
2540 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2541 ExitArgs(ExitArgs), Conditional(Conditional) {}
2542 void Enter(CodeGenFunction &CGF) override {
2543 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2544 if (Conditional) {
2545 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2546 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2547 ContBlock = CGF.createBasicBlock("omp_if.end");
2548 // Generate the branch (If-stmt)
2549 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2550 CGF.EmitBlock(ThenBlock);
2551 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002552 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002553 void Done(CodeGenFunction &CGF) {
2554 // Emit the rest of blocks/branches
2555 CGF.EmitBranch(ContBlock);
2556 CGF.EmitBlock(ContBlock, true);
2557 }
2558 void Exit(CodeGenFunction &CGF) override {
2559 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002560 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002561};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002562} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002563
2564void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2565 StringRef CriticalName,
2566 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002567 SourceLocation Loc, const Expr *Hint) {
2568 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002569 // CriticalOpGen();
2570 // __kmpc_end_critical(ident_t *, gtid, Lock);
2571 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002572 if (!CGF.HaveInsertPoint())
2573 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002574 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2575 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002576 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2577 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002578 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002579 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2580 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2581 }
2582 CommonActionTy Action(
2583 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2584 : OMPRTL__kmpc_critical),
2585 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2586 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002587 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002588}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002589
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002590void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002591 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002592 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002593 if (!CGF.HaveInsertPoint())
2594 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002595 // if(__kmpc_master(ident_t *, gtid)) {
2596 // MasterOpGen();
2597 // __kmpc_end_master(ident_t *, gtid);
2598 // }
2599 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002600 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002601 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2602 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2603 /*Conditional=*/true);
2604 MasterOpGen.setAction(Action);
2605 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2606 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002607}
2608
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002609void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2610 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002611 if (!CGF.HaveInsertPoint())
2612 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002613 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2614 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002615 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002616 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002617 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002618 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2619 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002620}
2621
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002622void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2623 const RegionCodeGenTy &TaskgroupOpGen,
2624 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002625 if (!CGF.HaveInsertPoint())
2626 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002627 // __kmpc_taskgroup(ident_t *, gtid);
2628 // TaskgroupOpGen();
2629 // __kmpc_end_taskgroup(ident_t *, gtid);
2630 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002631 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2632 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2633 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2634 Args);
2635 TaskgroupOpGen.setAction(Action);
2636 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002637}
2638
John McCall7f416cc2015-09-08 08:05:57 +00002639/// Given an array of pointers to variables, project the address of a
2640/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002641static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2642 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002643 // Pull out the pointer to the variable.
2644 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002645 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002646 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2647
2648 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002649 Addr = CGF.Builder.CreateElementBitCast(
2650 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002651 return Addr;
2652}
2653
Alexey Bataeva63048e2015-03-23 06:18:07 +00002654static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002655 CodeGenModule &CGM, llvm::Type *ArgsType,
2656 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2657 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002658 auto &C = CGM.getContext();
2659 // void copy_func(void *LHSArg, void *RHSArg);
2660 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002661 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2662 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002663 Args.push_back(&LHSArg);
2664 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002665 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002666 auto *Fn = llvm::Function::Create(
2667 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2668 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002669 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002670 CodeGenFunction CGF(CGM);
2671 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002672 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002673 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002674 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2675 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2676 ArgsType), CGF.getPointerAlign());
2677 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2678 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2679 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002680 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2681 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2682 // ...
2683 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002684 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002685 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2686 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2687
2688 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2689 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2690
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002691 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2692 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002693 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002694 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002695 CGF.FinishFunction();
2696 return Fn;
2697}
2698
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002699void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002700 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002701 SourceLocation Loc,
2702 ArrayRef<const Expr *> CopyprivateVars,
2703 ArrayRef<const Expr *> SrcExprs,
2704 ArrayRef<const Expr *> DstExprs,
2705 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002706 if (!CGF.HaveInsertPoint())
2707 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002708 assert(CopyprivateVars.size() == SrcExprs.size() &&
2709 CopyprivateVars.size() == DstExprs.size() &&
2710 CopyprivateVars.size() == AssignmentOps.size());
2711 auto &C = CGM.getContext();
2712 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002713 // if(__kmpc_single(ident_t *, gtid)) {
2714 // SingleOpGen();
2715 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002716 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002717 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002718 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2719 // <copy_func>, did_it);
2720
John McCall7f416cc2015-09-08 08:05:57 +00002721 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002722 if (!CopyprivateVars.empty()) {
2723 // int32 did_it = 0;
2724 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2725 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002726 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002727 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002728 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002729 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002730 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2731 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2732 /*Conditional=*/true);
2733 SingleOpGen.setAction(Action);
2734 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2735 if (DidIt.isValid()) {
2736 // did_it = 1;
2737 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2738 }
2739 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002740 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2741 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002742 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002743 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2744 auto CopyprivateArrayTy =
2745 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2746 /*IndexTypeQuals=*/0);
2747 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002748 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002749 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2750 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002751 Address Elem = CGF.Builder.CreateConstArrayGEP(
2752 CopyprivateList, I, CGF.getPointerSize());
2753 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002754 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002755 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2756 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002757 }
2758 // Build function that copies private values from single region to all other
2759 // threads in the corresponding parallel region.
2760 auto *CpyFn = emitCopyprivateCopyFunction(
2761 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002762 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002763 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002764 Address CL =
2765 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2766 CGF.VoidPtrTy);
2767 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002768 llvm::Value *Args[] = {
2769 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2770 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002771 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002772 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002773 CpyFn, // void (*) (void *, void *) <copy_func>
2774 DidItVal // i32 did_it
2775 };
2776 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2777 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002778}
2779
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002780void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2781 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002782 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002783 if (!CGF.HaveInsertPoint())
2784 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002785 // __kmpc_ordered(ident_t *, gtid);
2786 // OrderedOpGen();
2787 // __kmpc_end_ordered(ident_t *, gtid);
2788 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002789 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002790 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002791 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2792 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2793 Args);
2794 OrderedOpGen.setAction(Action);
2795 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2796 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002797 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002798 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002799}
2800
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002801void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002802 OpenMPDirectiveKind Kind, bool EmitChecks,
2803 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002804 if (!CGF.HaveInsertPoint())
2805 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002806 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002807 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002808 unsigned Flags;
2809 if (Kind == OMPD_for)
2810 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2811 else if (Kind == OMPD_sections)
2812 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2813 else if (Kind == OMPD_single)
2814 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2815 else if (Kind == OMPD_barrier)
2816 Flags = OMP_IDENT_BARRIER_EXPL;
2817 else
2818 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002819 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2820 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002821 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2822 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002823 if (auto *OMPRegionInfo =
2824 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002825 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002826 auto *Result = CGF.EmitRuntimeCall(
2827 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002828 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002829 // if (__kmpc_cancel_barrier()) {
2830 // exit from construct;
2831 // }
2832 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2833 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2834 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2835 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2836 CGF.EmitBlock(ExitBB);
2837 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002838 auto CancelDestination =
2839 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002840 CGF.EmitBranchThroughCleanup(CancelDestination);
2841 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2842 }
2843 return;
2844 }
2845 }
2846 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002847}
2848
Alexander Musmanc6388682014-12-15 07:07:06 +00002849/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2850static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002851 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002852 switch (ScheduleKind) {
2853 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002854 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2855 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002856 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002857 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002858 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002859 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002860 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002861 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2862 case OMPC_SCHEDULE_auto:
2863 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002864 case OMPC_SCHEDULE_unknown:
2865 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002866 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002867 }
2868 llvm_unreachable("Unexpected runtime schedule");
2869}
2870
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002871/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2872static OpenMPSchedType
2873getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2874 // only static is allowed for dist_schedule
2875 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2876}
2877
Alexander Musmanc6388682014-12-15 07:07:06 +00002878bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2879 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002880 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002881 return Schedule == OMP_sch_static;
2882}
2883
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002884bool CGOpenMPRuntime::isStaticNonchunked(
2885 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2886 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2887 return Schedule == OMP_dist_sch_static;
2888}
2889
2890
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002891bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002892 auto Schedule =
2893 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002894 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2895 return Schedule != OMP_sch_static;
2896}
2897
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002898static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2899 OpenMPScheduleClauseModifier M1,
2900 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002901 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002902 switch (M1) {
2903 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002904 Modifier = OMP_sch_modifier_monotonic;
2905 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002906 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002907 Modifier = OMP_sch_modifier_nonmonotonic;
2908 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002909 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002910 if (Schedule == OMP_sch_static_chunked)
2911 Schedule = OMP_sch_static_balanced_chunked;
2912 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002913 case OMPC_SCHEDULE_MODIFIER_last:
2914 case OMPC_SCHEDULE_MODIFIER_unknown:
2915 break;
2916 }
2917 switch (M2) {
2918 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002919 Modifier = OMP_sch_modifier_monotonic;
2920 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002921 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002922 Modifier = OMP_sch_modifier_nonmonotonic;
2923 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002924 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002925 if (Schedule == OMP_sch_static_chunked)
2926 Schedule = OMP_sch_static_balanced_chunked;
2927 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002928 case OMPC_SCHEDULE_MODIFIER_last:
2929 case OMPC_SCHEDULE_MODIFIER_unknown:
2930 break;
2931 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002932 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002933}
2934
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002935void CGOpenMPRuntime::emitForDispatchInit(
2936 CodeGenFunction &CGF, SourceLocation Loc,
2937 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2938 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002939 if (!CGF.HaveInsertPoint())
2940 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002941 OpenMPSchedType Schedule = getRuntimeSchedule(
2942 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002943 assert(Ordered ||
2944 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002945 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2946 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002947 // Call __kmpc_dispatch_init(
2948 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2949 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2950 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002951
John McCall7f416cc2015-09-08 08:05:57 +00002952 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002953 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2954 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002955 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002956 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2957 CGF.Builder.getInt32(addMonoNonMonoModifier(
2958 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002959 DispatchValues.LB, // Lower
2960 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002961 CGF.Builder.getIntN(IVSize, 1), // Stride
2962 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002963 };
2964 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2965}
2966
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002967static void emitForStaticInitCall(
2968 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2969 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2970 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002971 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002972 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002973 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002974
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002975 assert(!Values.Ordered);
2976 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2977 Schedule == OMP_sch_static_balanced_chunked ||
2978 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2979 Schedule == OMP_dist_sch_static ||
2980 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002981
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002982 // Call __kmpc_for_static_init(
2983 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2984 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2985 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2986 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2987 llvm::Value *Chunk = Values.Chunk;
2988 if (Chunk == nullptr) {
2989 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2990 Schedule == OMP_dist_sch_static) &&
2991 "expected static non-chunked schedule");
2992 // If the Chunk was not specified in the clause - use default value 1.
2993 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
2994 } else {
2995 assert((Schedule == OMP_sch_static_chunked ||
2996 Schedule == OMP_sch_static_balanced_chunked ||
2997 Schedule == OMP_ord_static_chunked ||
2998 Schedule == OMP_dist_sch_static_chunked) &&
2999 "expected static chunked schedule");
3000 }
3001 llvm::Value *Args[] = {
3002 UpdateLocation,
3003 ThreadId,
3004 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3005 M2)), // Schedule type
3006 Values.IL.getPointer(), // &isLastIter
3007 Values.LB.getPointer(), // &LB
3008 Values.UB.getPointer(), // &UB
3009 Values.ST.getPointer(), // &Stride
3010 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3011 Chunk // Chunk
3012 };
3013 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003014}
3015
John McCall7f416cc2015-09-08 08:05:57 +00003016void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3017 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003018 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003019 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003020 const StaticRTInput &Values) {
3021 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3022 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3023 assert(isOpenMPWorksharingDirective(DKind) &&
3024 "Expected loop-based or sections-based directive.");
3025 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3026 isOpenMPLoopDirective(DKind)
3027 ? OMP_IDENT_WORK_LOOP
3028 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003029 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003030 auto *StaticInitFunction =
3031 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003032 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003033 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003034}
John McCall7f416cc2015-09-08 08:05:57 +00003035
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003036void CGOpenMPRuntime::emitDistributeStaticInit(
3037 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003038 OpenMPDistScheduleClauseKind SchedKind,
3039 const CGOpenMPRuntime::StaticRTInput &Values) {
3040 OpenMPSchedType ScheduleNum =
3041 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3042 auto *UpdatedLocation =
3043 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003044 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003045 auto *StaticInitFunction =
3046 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003047 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3048 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003049 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003050}
3051
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003052void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003053 SourceLocation Loc,
3054 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003055 if (!CGF.HaveInsertPoint())
3056 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003057 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003058 llvm::Value *Args[] = {
3059 emitUpdateLocation(CGF, Loc,
3060 isOpenMPDistributeDirective(DKind)
3061 ? OMP_IDENT_WORK_DISTRIBUTE
3062 : isOpenMPLoopDirective(DKind)
3063 ? OMP_IDENT_WORK_LOOP
3064 : OMP_IDENT_WORK_SECTIONS),
3065 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003066 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3067 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003068}
3069
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003070void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3071 SourceLocation Loc,
3072 unsigned IVSize,
3073 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003074 if (!CGF.HaveInsertPoint())
3075 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003076 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003077 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003078 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3079}
3080
Alexander Musman92bdaab2015-03-12 13:37:50 +00003081llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3082 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003083 bool IVSigned, Address IL,
3084 Address LB, Address UB,
3085 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003086 // Call __kmpc_dispatch_next(
3087 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3088 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3089 // kmp_int[32|64] *p_stride);
3090 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003091 emitUpdateLocation(CGF, Loc),
3092 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003093 IL.getPointer(), // &isLastIter
3094 LB.getPointer(), // &Lower
3095 UB.getPointer(), // &Upper
3096 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003097 };
3098 llvm::Value *Call =
3099 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3100 return CGF.EmitScalarConversion(
3101 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003102 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003103}
3104
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003105void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3106 llvm::Value *NumThreads,
3107 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003108 if (!CGF.HaveInsertPoint())
3109 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003110 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3111 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003112 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003113 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003114 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3115 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003116}
3117
Alexey Bataev7f210c62015-06-18 13:40:03 +00003118void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3119 OpenMPProcBindClauseKind ProcBind,
3120 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003121 if (!CGF.HaveInsertPoint())
3122 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003123 // Constants for proc bind value accepted by the runtime.
3124 enum ProcBindTy {
3125 ProcBindFalse = 0,
3126 ProcBindTrue,
3127 ProcBindMaster,
3128 ProcBindClose,
3129 ProcBindSpread,
3130 ProcBindIntel,
3131 ProcBindDefault
3132 } RuntimeProcBind;
3133 switch (ProcBind) {
3134 case OMPC_PROC_BIND_master:
3135 RuntimeProcBind = ProcBindMaster;
3136 break;
3137 case OMPC_PROC_BIND_close:
3138 RuntimeProcBind = ProcBindClose;
3139 break;
3140 case OMPC_PROC_BIND_spread:
3141 RuntimeProcBind = ProcBindSpread;
3142 break;
3143 case OMPC_PROC_BIND_unknown:
3144 llvm_unreachable("Unsupported proc_bind value.");
3145 }
3146 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3147 llvm::Value *Args[] = {
3148 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3149 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3150 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3151}
3152
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003153void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3154 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003155 if (!CGF.HaveInsertPoint())
3156 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003157 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003158 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3159 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003160}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003161
Alexey Bataev62b63b12015-03-10 07:28:44 +00003162namespace {
3163/// \brief Indexes of fields for type kmp_task_t.
3164enum KmpTaskTFields {
3165 /// \brief List of shared variables.
3166 KmpTaskTShareds,
3167 /// \brief Task routine.
3168 KmpTaskTRoutine,
3169 /// \brief Partition id for the untied tasks.
3170 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003171 /// Function with call of destructors for private variables.
3172 Data1,
3173 /// Task priority.
3174 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003175 /// (Taskloops only) Lower bound.
3176 KmpTaskTLowerBound,
3177 /// (Taskloops only) Upper bound.
3178 KmpTaskTUpperBound,
3179 /// (Taskloops only) Stride.
3180 KmpTaskTStride,
3181 /// (Taskloops only) Is last iteration flag.
3182 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003183 /// (Taskloops only) Reduction data.
3184 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003185};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003186} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003187
Samuel Antaoee8fb302016-01-06 13:42:12 +00003188bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3189 // FIXME: Add other entries type when they become supported.
3190 return OffloadEntriesTargetRegion.empty();
3191}
3192
3193/// \brief Initialize target region entry.
3194void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3195 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3196 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003197 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003198 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3199 "only required for the device "
3200 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003201 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003202 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3203 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003204 ++OffloadingEntriesNum;
3205}
3206
3207void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3208 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3209 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003210 llvm::Constant *Addr, llvm::Constant *ID,
3211 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003212 // If we are emitting code for a target, the entry is already initialized,
3213 // only has to be registered.
3214 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003215 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003216 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003217 auto &Entry =
3218 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003219 assert(Entry.isValid() && "Entry not initialized!");
3220 Entry.setAddress(Addr);
3221 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003222 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003223 return;
3224 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003225 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003226 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003227 }
3228}
3229
3230bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003231 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3232 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003233 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3234 if (PerDevice == OffloadEntriesTargetRegion.end())
3235 return false;
3236 auto PerFile = PerDevice->second.find(FileID);
3237 if (PerFile == PerDevice->second.end())
3238 return false;
3239 auto PerParentName = PerFile->second.find(ParentName);
3240 if (PerParentName == PerFile->second.end())
3241 return false;
3242 auto PerLine = PerParentName->second.find(LineNum);
3243 if (PerLine == PerParentName->second.end())
3244 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003245 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003246 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003247 return false;
3248 return true;
3249}
3250
3251void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3252 const OffloadTargetRegionEntryInfoActTy &Action) {
3253 // Scan all target region entries and perform the provided action.
3254 for (auto &D : OffloadEntriesTargetRegion)
3255 for (auto &F : D.second)
3256 for (auto &P : F.second)
3257 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003258 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003259}
3260
3261/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3262/// \a Codegen. This is used to emit the two functions that register and
3263/// unregister the descriptor of the current compilation unit.
3264static llvm::Function *
3265createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3266 const RegionCodeGenTy &Codegen) {
3267 auto &C = CGM.getContext();
3268 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003269 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003270 Args.push_back(&DummyPtr);
3271
3272 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003273 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003274 auto FTy = CGM.getTypes().GetFunctionType(FI);
3275 auto *Fn =
3276 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3277 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3278 Codegen(CGF);
3279 CGF.FinishFunction();
3280 return Fn;
3281}
3282
3283llvm::Function *
3284CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3285
3286 // If we don't have entries or if we are emitting code for the device, we
3287 // don't need to do anything.
3288 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3289 return nullptr;
3290
3291 auto &M = CGM.getModule();
3292 auto &C = CGM.getContext();
3293
3294 // Get list of devices we care about
3295 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3296
3297 // We should be creating an offloading descriptor only if there are devices
3298 // specified.
3299 assert(!Devices.empty() && "No OpenMP offloading devices??");
3300
3301 // Create the external variables that will point to the begin and end of the
3302 // host entries section. These will be defined by the linker.
3303 auto *OffloadEntryTy =
3304 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3305 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3306 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003307 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003308 ".omp_offloading.entries_begin");
3309 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3310 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003311 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003312 ".omp_offloading.entries_end");
3313
3314 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003315 auto *DeviceImageTy = cast<llvm::StructType>(
3316 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003317 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003318 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003319
3320 for (unsigned i = 0; i < Devices.size(); ++i) {
3321 StringRef T = Devices[i].getTriple();
3322 auto *ImgBegin = new llvm::GlobalVariable(
3323 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003324 /*Initializer=*/nullptr,
3325 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003326 auto *ImgEnd = new llvm::GlobalVariable(
3327 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003328 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003329
John McCall6c9f1fdb2016-11-19 08:17:24 +00003330 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3331 Dev.add(ImgBegin);
3332 Dev.add(ImgEnd);
3333 Dev.add(HostEntriesBegin);
3334 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003335 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003336 }
3337
3338 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003339 llvm::GlobalVariable *DeviceImages =
3340 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3341 CGM.getPointerAlign(),
3342 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003343 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003344
3345 // This is a Zero array to be used in the creation of the constant expressions
3346 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3347 llvm::Constant::getNullValue(CGM.Int32Ty)};
3348
3349 // Create the target region descriptor.
3350 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3351 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003352 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003353 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3354 DescInit.addInt(CGM.Int32Ty, Devices.size());
3355 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3356 DeviceImages,
3357 Index));
3358 DescInit.add(HostEntriesBegin);
3359 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003360
John McCall6c9f1fdb2016-11-19 08:17:24 +00003361 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3362 CGM.getPointerAlign(),
3363 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003364
3365 // Emit code to register or unregister the descriptor at execution
3366 // startup or closing, respectively.
3367
3368 // Create a variable to drive the registration and unregistration of the
3369 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3370 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3371 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003372 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003373
3374 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003375 CGM, ".omp_offloading.descriptor_unreg",
3376 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003377 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3378 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003379 });
3380 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003381 CGM, ".omp_offloading.descriptor_reg",
3382 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003383 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3384 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003385 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3386 });
George Rokos29d0f002017-05-27 03:03:13 +00003387 if (CGM.supportsCOMDAT()) {
3388 // It is sufficient to call registration function only once, so create a
3389 // COMDAT group for registration/unregistration functions and associated
3390 // data. That would reduce startup time and code size. Registration
3391 // function serves as a COMDAT group key.
3392 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3393 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3394 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3395 RegFn->setComdat(ComdatKey);
3396 UnRegFn->setComdat(ComdatKey);
3397 DeviceImages->setComdat(ComdatKey);
3398 Desc->setComdat(ComdatKey);
3399 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003400 return RegFn;
3401}
3402
Samuel Antao2de62b02016-02-13 23:35:10 +00003403void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003404 llvm::Constant *Addr, uint64_t Size,
3405 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003406 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003407 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3408 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3409 llvm::LLVMContext &C = CGM.getModule().getContext();
3410 llvm::Module &M = CGM.getModule();
3411
3412 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003413 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003414
3415 // Create constant string with the name.
3416 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3417
3418 llvm::GlobalVariable *Str =
3419 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3420 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3421 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003422 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003423 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3424
John McCall6c9f1fdb2016-11-19 08:17:24 +00003425 // We can't have any padding between symbols, so we need to have 1-byte
3426 // alignment.
3427 auto Align = CharUnits::fromQuantity(1);
3428
Samuel Antaoee8fb302016-01-06 13:42:12 +00003429 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003430 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003431 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3432 EntryInit.add(AddrPtr);
3433 EntryInit.add(StrPtr);
3434 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003435 EntryInit.addInt(CGM.Int32Ty, Flags);
3436 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003437 llvm::GlobalVariable *Entry =
3438 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3439 Align,
3440 /*constant*/ true,
3441 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003442
3443 // The entry has to be created in the section the linker expects it to be.
3444 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003445}
3446
3447void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3448 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003449 // can easily figure out what to emit. The produced metadata looks like
3450 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003451 //
3452 // !omp_offload.info = !{!1, ...}
3453 //
3454 // Right now we only generate metadata for function that contain target
3455 // regions.
3456
3457 // If we do not have entries, we dont need to do anything.
3458 if (OffloadEntriesInfoManager.empty())
3459 return;
3460
3461 llvm::Module &M = CGM.getModule();
3462 llvm::LLVMContext &C = M.getContext();
3463 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3464 OrderedEntries(OffloadEntriesInfoManager.size());
3465
3466 // Create the offloading info metadata node.
3467 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3468
Simon Pilgrim2c518802017-03-30 14:13:19 +00003469 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003470 auto getMDInt = [&](unsigned v) {
3471 return llvm::ConstantAsMetadata::get(
3472 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3473 };
3474
3475 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3476
3477 // Create function that emits metadata for each target region entry;
3478 auto &&TargetRegionMetadataEmitter = [&](
3479 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003480 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3481 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3482 // Generate metadata for target regions. Each entry of this metadata
3483 // contains:
3484 // - Entry 0 -> Kind of this type of metadata (0).
3485 // - Entry 1 -> Device ID of the file where the entry was identified.
3486 // - Entry 2 -> File ID of the file where the entry was identified.
3487 // - Entry 3 -> Mangled name of the function where the entry was identified.
3488 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003489 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003490 // The first element of the metadata node is the kind.
3491 Ops.push_back(getMDInt(E.getKind()));
3492 Ops.push_back(getMDInt(DeviceID));
3493 Ops.push_back(getMDInt(FileID));
3494 Ops.push_back(getMDString(ParentName));
3495 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003496 Ops.push_back(getMDInt(E.getOrder()));
3497
3498 // Save this entry in the right position of the ordered entries array.
3499 OrderedEntries[E.getOrder()] = &E;
3500
3501 // Add metadata to the named metadata node.
3502 MD->addOperand(llvm::MDNode::get(C, Ops));
3503 };
3504
3505 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3506 TargetRegionMetadataEmitter);
3507
3508 for (auto *E : OrderedEntries) {
3509 assert(E && "All ordered entries must exist!");
3510 if (auto *CE =
3511 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3512 E)) {
3513 assert(CE->getID() && CE->getAddress() &&
3514 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003515 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003516 } else
3517 llvm_unreachable("Unsupported entry kind.");
3518 }
3519}
3520
3521/// \brief Loads all the offload entries information from the host IR
3522/// metadata.
3523void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3524 // If we are in target mode, load the metadata from the host IR. This code has
3525 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3526
3527 if (!CGM.getLangOpts().OpenMPIsDevice)
3528 return;
3529
3530 if (CGM.getLangOpts().OMPHostIRFile.empty())
3531 return;
3532
3533 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3534 if (Buf.getError())
3535 return;
3536
3537 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003538 auto ME = expectedToErrorOrAndEmitErrors(
3539 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003540
3541 if (ME.getError())
3542 return;
3543
3544 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3545 if (!MD)
3546 return;
3547
3548 for (auto I : MD->operands()) {
3549 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3550
3551 auto getMDInt = [&](unsigned Idx) {
3552 llvm::ConstantAsMetadata *V =
3553 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3554 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3555 };
3556
3557 auto getMDString = [&](unsigned Idx) {
3558 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3559 return V->getString();
3560 };
3561
3562 switch (getMDInt(0)) {
3563 default:
3564 llvm_unreachable("Unexpected metadata!");
3565 break;
3566 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3567 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3568 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3569 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3570 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003571 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003572 break;
3573 }
3574 }
3575}
3576
Alexey Bataev62b63b12015-03-10 07:28:44 +00003577void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3578 if (!KmpRoutineEntryPtrTy) {
3579 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3580 auto &C = CGM.getContext();
3581 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3582 FunctionProtoType::ExtProtoInfo EPI;
3583 KmpRoutineEntryPtrQTy = C.getPointerType(
3584 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3585 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3586 }
3587}
3588
Alexey Bataevc71a4092015-09-11 10:29:41 +00003589static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3590 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003591 auto *Field = FieldDecl::Create(
3592 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3593 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3594 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3595 Field->setAccess(AS_public);
3596 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003597 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003598}
3599
Samuel Antaoee8fb302016-01-06 13:42:12 +00003600QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3601
3602 // Make sure the type of the entry is already created. This is the type we
3603 // have to create:
3604 // struct __tgt_offload_entry{
3605 // void *addr; // Pointer to the offload entry info.
3606 // // (function or global)
3607 // char *name; // Name of the function or global.
3608 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003609 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3610 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003611 // };
3612 if (TgtOffloadEntryQTy.isNull()) {
3613 ASTContext &C = CGM.getContext();
3614 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3615 RD->startDefinition();
3616 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3617 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3618 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003619 addFieldToRecordDecl(
3620 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3621 addFieldToRecordDecl(
3622 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003623 RD->completeDefinition();
3624 TgtOffloadEntryQTy = C.getRecordType(RD);
3625 }
3626 return TgtOffloadEntryQTy;
3627}
3628
3629QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3630 // These are the types we need to build:
3631 // struct __tgt_device_image{
3632 // void *ImageStart; // Pointer to the target code start.
3633 // void *ImageEnd; // Pointer to the target code end.
3634 // // We also add the host entries to the device image, as it may be useful
3635 // // for the target runtime to have access to that information.
3636 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3637 // // the entries.
3638 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3639 // // entries (non inclusive).
3640 // };
3641 if (TgtDeviceImageQTy.isNull()) {
3642 ASTContext &C = CGM.getContext();
3643 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3644 RD->startDefinition();
3645 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3646 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3647 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3648 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3649 RD->completeDefinition();
3650 TgtDeviceImageQTy = C.getRecordType(RD);
3651 }
3652 return TgtDeviceImageQTy;
3653}
3654
3655QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3656 // struct __tgt_bin_desc{
3657 // int32_t NumDevices; // Number of devices supported.
3658 // __tgt_device_image *DeviceImages; // Arrays of device images
3659 // // (one per device).
3660 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3661 // // entries.
3662 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3663 // // entries (non inclusive).
3664 // };
3665 if (TgtBinaryDescriptorQTy.isNull()) {
3666 ASTContext &C = CGM.getContext();
3667 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3668 RD->startDefinition();
3669 addFieldToRecordDecl(
3670 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3671 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3672 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3673 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3674 RD->completeDefinition();
3675 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3676 }
3677 return TgtBinaryDescriptorQTy;
3678}
3679
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003680namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003681struct PrivateHelpersTy {
3682 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3683 const VarDecl *PrivateElemInit)
3684 : Original(Original), PrivateCopy(PrivateCopy),
3685 PrivateElemInit(PrivateElemInit) {}
3686 const VarDecl *Original;
3687 const VarDecl *PrivateCopy;
3688 const VarDecl *PrivateElemInit;
3689};
3690typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003691} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003692
Alexey Bataev9e034042015-05-05 04:05:12 +00003693static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003694createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003695 if (!Privates.empty()) {
3696 auto &C = CGM.getContext();
3697 // Build struct .kmp_privates_t. {
3698 // /* private vars */
3699 // };
3700 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3701 RD->startDefinition();
3702 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003703 auto *VD = Pair.second.Original;
3704 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003705 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003706 auto *FD = addFieldToRecordDecl(C, RD, Type);
3707 if (VD->hasAttrs()) {
3708 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3709 E(VD->getAttrs().end());
3710 I != E; ++I)
3711 FD->addAttr(*I);
3712 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003713 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003714 RD->completeDefinition();
3715 return RD;
3716 }
3717 return nullptr;
3718}
3719
Alexey Bataev9e034042015-05-05 04:05:12 +00003720static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003721createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3722 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003723 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003724 auto &C = CGM.getContext();
3725 // Build struct kmp_task_t {
3726 // void * shareds;
3727 // kmp_routine_entry_t routine;
3728 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003729 // kmp_cmplrdata_t data1;
3730 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003731 // For taskloops additional fields:
3732 // kmp_uint64 lb;
3733 // kmp_uint64 ub;
3734 // kmp_int64 st;
3735 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003736 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003737 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003738 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3739 UD->startDefinition();
3740 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3741 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3742 UD->completeDefinition();
3743 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003744 auto *RD = C.buildImplicitRecord("kmp_task_t");
3745 RD->startDefinition();
3746 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3747 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3748 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003749 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3750 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003751 if (isOpenMPTaskLoopDirective(Kind)) {
3752 QualType KmpUInt64Ty =
3753 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3754 QualType KmpInt64Ty =
3755 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3756 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3757 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3758 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3759 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003760 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003761 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003762 RD->completeDefinition();
3763 return RD;
3764}
3765
3766static RecordDecl *
3767createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003768 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003769 auto &C = CGM.getContext();
3770 // Build struct kmp_task_t_with_privates {
3771 // kmp_task_t task_data;
3772 // .kmp_privates_t. privates;
3773 // };
3774 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3775 RD->startDefinition();
3776 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003777 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3778 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3779 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003780 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003781 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003782}
3783
3784/// \brief Emit a proxy function which accepts kmp_task_t as the second
3785/// argument.
3786/// \code
3787/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003788/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003789/// For taskloops:
3790/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003791/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003792/// return 0;
3793/// }
3794/// \endcode
3795static llvm::Value *
3796emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003797 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3798 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003799 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003800 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3801 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003802 auto &C = CGM.getContext();
3803 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003804 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3805 ImplicitParamDecl::Other);
3806 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3807 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3808 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003809 Args.push_back(&GtidArg);
3810 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003811 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003812 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003813 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3814 auto *TaskEntry =
3815 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3816 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003817 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003818 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003819 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3820
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003821 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003822 // tt,
3823 // For taskloops:
3824 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3825 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003826 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003827 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003828 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3829 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3830 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003831 auto *KmpTaskTWithPrivatesQTyRD =
3832 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003833 LValue Base =
3834 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003835 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3836 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3837 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003838 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003839
3840 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3841 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003842 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003843 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003844 CGF.ConvertTypeForMem(SharedsPtrTy));
3845
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003846 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3847 llvm::Value *PrivatesParam;
3848 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3849 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3850 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003851 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003852 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003853 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003854
Alexey Bataev7292c292016-04-25 12:22:29 +00003855 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3856 TaskPrivatesMap,
3857 CGF.Builder
3858 .CreatePointerBitCastOrAddrSpaceCast(
3859 TDBase.getAddress(), CGF.VoidPtrTy)
3860 .getPointer()};
3861 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3862 std::end(CommonArgs));
3863 if (isOpenMPTaskLoopDirective(Kind)) {
3864 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3865 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3866 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3867 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3868 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3869 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3870 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3871 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3872 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3873 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3874 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3875 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003876 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3877 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3878 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003879 CallArgs.push_back(LBParam);
3880 CallArgs.push_back(UBParam);
3881 CallArgs.push_back(StParam);
3882 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003883 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003884 }
3885 CallArgs.push_back(SharedsParam);
3886
Alexey Bataev3c595a62017-08-14 15:01:03 +00003887 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3888 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003889 CGF.EmitStoreThroughLValue(
3890 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003891 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003892 CGF.FinishFunction();
3893 return TaskEntry;
3894}
3895
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003896static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3897 SourceLocation Loc,
3898 QualType KmpInt32Ty,
3899 QualType KmpTaskTWithPrivatesPtrQTy,
3900 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003901 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003902 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003903 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3904 ImplicitParamDecl::Other);
3905 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3906 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3907 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003908 Args.push_back(&GtidArg);
3909 Args.push_back(&TaskTypeArg);
3910 FunctionType::ExtInfo Info;
3911 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003912 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003913 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3914 auto *DestructorFn =
3915 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3916 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003917 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3918 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003919 CodeGenFunction CGF(CGM);
3920 CGF.disableDebugInfo();
3921 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3922 Args);
3923
Alexey Bataev31300ed2016-02-04 11:27:03 +00003924 LValue Base = CGF.EmitLoadOfPointerLValue(
3925 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3926 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003927 auto *KmpTaskTWithPrivatesQTyRD =
3928 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3929 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003930 Base = CGF.EmitLValueForField(Base, *FI);
3931 for (auto *Field :
3932 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3933 if (auto DtorKind = Field->getType().isDestructedType()) {
3934 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3935 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3936 }
3937 }
3938 CGF.FinishFunction();
3939 return DestructorFn;
3940}
3941
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003942/// \brief Emit a privates mapping function for correct handling of private and
3943/// firstprivate variables.
3944/// \code
3945/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3946/// **noalias priv1,..., <tyn> **noalias privn) {
3947/// *priv1 = &.privates.priv1;
3948/// ...;
3949/// *privn = &.privates.privn;
3950/// }
3951/// \endcode
3952static llvm::Value *
3953emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003954 ArrayRef<const Expr *> PrivateVars,
3955 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003956 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003957 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003958 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003959 auto &C = CGM.getContext();
3960 FunctionArgList Args;
3961 ImplicitParamDecl TaskPrivatesArg(
3962 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003963 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3964 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003965 Args.push_back(&TaskPrivatesArg);
3966 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3967 unsigned Counter = 1;
3968 for (auto *E: PrivateVars) {
3969 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003970 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3971 C.getPointerType(C.getPointerType(E->getType()))
3972 .withConst()
3973 .withRestrict(),
3974 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003975 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3976 PrivateVarsPos[VD] = Counter;
3977 ++Counter;
3978 }
3979 for (auto *E : FirstprivateVars) {
3980 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003981 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3982 C.getPointerType(C.getPointerType(E->getType()))
3983 .withConst()
3984 .withRestrict(),
3985 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003986 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3987 PrivateVarsPos[VD] = Counter;
3988 ++Counter;
3989 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003990 for (auto *E: LastprivateVars) {
3991 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003992 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3993 C.getPointerType(C.getPointerType(E->getType()))
3994 .withConst()
3995 .withRestrict(),
3996 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003997 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3998 PrivateVarsPos[VD] = Counter;
3999 ++Counter;
4000 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004001 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004002 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004003 auto *TaskPrivatesMapTy =
4004 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4005 auto *TaskPrivatesMap = llvm::Function::Create(
4006 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4007 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004008 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4009 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004010 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004011 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004012 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004013 CodeGenFunction CGF(CGM);
4014 CGF.disableDebugInfo();
4015 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4016 TaskPrivatesMapFnInfo, Args);
4017
4018 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004019 LValue Base = CGF.EmitLoadOfPointerLValue(
4020 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4021 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004022 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4023 Counter = 0;
4024 for (auto *Field : PrivatesQTyRD->fields()) {
4025 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4026 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004027 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004028 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4029 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004030 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004031 ++Counter;
4032 }
4033 CGF.FinishFunction();
4034 return TaskPrivatesMap;
4035}
4036
Alexey Bataev9e034042015-05-05 04:05:12 +00004037static int array_pod_sort_comparator(const PrivateDataTy *P1,
4038 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004039 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4040}
4041
Alexey Bataevf93095a2016-05-05 08:46:22 +00004042/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004043static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004044 const OMPExecutableDirective &D,
4045 Address KmpTaskSharedsPtr, LValue TDBase,
4046 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4047 QualType SharedsTy, QualType SharedsPtrTy,
4048 const OMPTaskDataTy &Data,
4049 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4050 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004051 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4052 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4053 LValue SrcBase;
4054 if (!Data.FirstprivateVars.empty()) {
4055 SrcBase = CGF.MakeAddrLValue(
4056 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4057 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4058 SharedsTy);
4059 }
4060 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4061 cast<CapturedStmt>(*D.getAssociatedStmt()));
4062 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4063 for (auto &&Pair : Privates) {
4064 auto *VD = Pair.second.PrivateCopy;
4065 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004066 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4067 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004068 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004069 if (auto *Elem = Pair.second.PrivateElemInit) {
4070 auto *OriginalVD = Pair.second.Original;
4071 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4072 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4073 SharedRefLValue = CGF.MakeAddrLValue(
4074 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004075 SharedRefLValue.getType(),
4076 LValueBaseInfo(AlignmentSource::Decl,
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004077 SharedRefLValue.getBaseInfo().getMayAlias()),
4078 CGF.CGM.getTBAAAccessInfo(SharedRefLValue.getType()));
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).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004274 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4275 if (SavedKmpTaskloopTQTy.isNull()) {
4276 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4277 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4278 }
4279 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004280 } else {
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004281 assert(D.getDirectiveKind() == OMPD_task &&
4282 "Expected taskloop or task directive");
4283 if (SavedKmpTaskTQTy.isNull()) {
4284 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4285 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4286 }
4287 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004288 }
4289 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004290 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004291 auto *KmpTaskTWithPrivatesQTyRD =
4292 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4293 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4294 QualType KmpTaskTWithPrivatesPtrQTy =
4295 C.getPointerType(KmpTaskTWithPrivatesQTy);
4296 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4297 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004298 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004299 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4300
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004301 // Emit initial values for private copies (if any).
4302 llvm::Value *TaskPrivatesMap = nullptr;
4303 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004304 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004305 if (!Privates.empty()) {
4306 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004307 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4308 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4309 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004310 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4311 TaskPrivatesMap, TaskPrivatesMapTy);
4312 } else {
4313 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4314 cast<llvm::PointerType>(TaskPrivatesMapTy));
4315 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004316 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4317 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004318 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004319 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4320 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4321 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004322
4323 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4324 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4325 // kmp_routine_entry_t *task_entry);
4326 // Task flags. Format is taken from
4327 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4328 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004329 enum {
4330 TiedFlag = 0x1,
4331 FinalFlag = 0x2,
4332 DestructorsFlag = 0x8,
4333 PriorityFlag = 0x20
4334 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004335 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004336 bool NeedsCleanup = false;
4337 if (!Privates.empty()) {
4338 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4339 if (NeedsCleanup)
4340 Flags = Flags | DestructorsFlag;
4341 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004342 if (Data.Priority.getInt())
4343 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004344 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004345 Data.Final.getPointer()
4346 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004347 CGF.Builder.getInt32(FinalFlag),
4348 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004349 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004350 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004351 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004352 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4353 getThreadID(CGF, Loc), TaskFlags,
4354 KmpTaskTWithPrivatesTySize, SharedsSize,
4355 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4356 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004357 auto *NewTask = CGF.EmitRuntimeCall(
4358 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004359 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4360 NewTask, KmpTaskTWithPrivatesPtrTy);
4361 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4362 KmpTaskTWithPrivatesQTy);
4363 LValue TDBase =
4364 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004365 // Fill the data in the resulting kmp_task_t record.
4366 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004367 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004368 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004369 KmpTaskSharedsPtr =
4370 Address(CGF.EmitLoadOfScalar(
4371 CGF.EmitLValueForField(
4372 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4373 KmpTaskTShareds)),
4374 Loc),
4375 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004376 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004377 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004378 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004379 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004380 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004381 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4382 SharedsTy, SharedsPtrTy, Data, Privates,
4383 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004384 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4385 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4386 Result.TaskDupFn = emitTaskDupFunction(
4387 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4388 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4389 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004390 }
4391 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004392 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4393 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004394 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004395 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4396 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4397 if (NeedsCleanup) {
4398 llvm::Value *DestructorFn = emitDestructorsFunction(
4399 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4400 KmpTaskTWithPrivatesQTy);
4401 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4402 LValue DestructorsLV = CGF.EmitLValueForField(
4403 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4404 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4405 DestructorFn, KmpRoutineEntryPtrTy),
4406 DestructorsLV);
4407 }
4408 // Set priority.
4409 if (Data.Priority.getInt()) {
4410 LValue Data2LV = CGF.EmitLValueForField(
4411 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4412 LValue PriorityLV = CGF.EmitLValueForField(
4413 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4414 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4415 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004416 Result.NewTask = NewTask;
4417 Result.TaskEntry = TaskEntry;
4418 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4419 Result.TDBase = TDBase;
4420 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4421 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004422}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004423
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004424void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4425 const OMPExecutableDirective &D,
4426 llvm::Value *TaskFunction,
4427 QualType SharedsTy, Address Shareds,
4428 const Expr *IfCond,
4429 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004430 if (!CGF.HaveInsertPoint())
4431 return;
4432
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004433 TaskResultTy Result =
4434 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4435 llvm::Value *NewTask = Result.NewTask;
4436 llvm::Value *TaskEntry = Result.TaskEntry;
4437 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4438 LValue TDBase = Result.TDBase;
4439 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004440 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004441 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004442 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004443 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004444 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004445 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004446 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004447 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4448 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004449 QualType FlagsTy =
4450 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004451 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4452 if (KmpDependInfoTy.isNull()) {
4453 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4454 KmpDependInfoRD->startDefinition();
4455 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4456 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4457 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4458 KmpDependInfoRD->completeDefinition();
4459 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004460 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004461 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004462 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004463 // Define type kmp_depend_info[<Dependences.size()>];
4464 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004465 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004466 ArrayType::Normal, /*IndexTypeQuals=*/0);
4467 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004468 DependenciesArray =
4469 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004470 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004471 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004472 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004473 llvm::Value *Size;
4474 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004475 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4476 LValue UpAddrLVal =
4477 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4478 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004479 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004480 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004481 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004482 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4483 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004484 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004485 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004486 auto Base = CGF.MakeAddrLValue(
4487 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004488 KmpDependInfoTy);
4489 // deps[i].base_addr = &<Dependences[i].second>;
4490 auto BaseAddrLVal = CGF.EmitLValueForField(
4491 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004492 CGF.EmitStoreOfScalar(
4493 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4494 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004495 // deps[i].len = sizeof(<Dependences[i].second>);
4496 auto LenLVal = CGF.EmitLValueForField(
4497 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4498 CGF.EmitStoreOfScalar(Size, LenLVal);
4499 // deps[i].flags = <Dependences[i].first>;
4500 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004501 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004502 case OMPC_DEPEND_in:
4503 DepKind = DepIn;
4504 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004505 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004506 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004507 case OMPC_DEPEND_inout:
4508 DepKind = DepInOut;
4509 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004510 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004511 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004512 case OMPC_DEPEND_unknown:
4513 llvm_unreachable("Unknown task dependence type");
4514 }
4515 auto FlagsLVal = CGF.EmitLValueForField(
4516 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4517 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4518 FlagsLVal);
4519 }
John McCall7f416cc2015-09-08 08:05:57 +00004520 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4521 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004522 CGF.VoidPtrTy);
4523 }
4524
Alexey Bataev62b63b12015-03-10 07:28:44 +00004525 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4526 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004527 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4528 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4529 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4530 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004531 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004532 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004533 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4534 llvm::Value *DepTaskArgs[7];
4535 if (NumDependencies) {
4536 DepTaskArgs[0] = UpLoc;
4537 DepTaskArgs[1] = ThreadID;
4538 DepTaskArgs[2] = NewTask;
4539 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4540 DepTaskArgs[4] = DependenciesArray.getPointer();
4541 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4542 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4543 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004544 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4545 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004546 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004547 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004548 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4549 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4550 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4551 }
John McCall7f416cc2015-09-08 08:05:57 +00004552 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004553 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004554 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004555 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004556 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004557 TaskArgs);
4558 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004559 // Check if parent region is untied and build return for untied task;
4560 if (auto *Region =
4561 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4562 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004563 };
John McCall7f416cc2015-09-08 08:05:57 +00004564
4565 llvm::Value *DepWaitTaskArgs[6];
4566 if (NumDependencies) {
4567 DepWaitTaskArgs[0] = UpLoc;
4568 DepWaitTaskArgs[1] = ThreadID;
4569 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4570 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4571 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4572 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4573 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004574 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004575 NumDependencies, &DepWaitTaskArgs,
4576 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004577 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004578 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4579 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4580 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4581 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4582 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004583 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004584 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004585 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004586 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004587 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4588 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004589 Action.Enter(CGF);
4590 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004591 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004592 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004593 };
4594
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004595 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4596 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004597 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4598 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004599 RegionCodeGenTy RCG(CodeGen);
4600 CommonActionTy Action(
4601 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4602 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4603 RCG.setAction(Action);
4604 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004605 };
John McCall7f416cc2015-09-08 08:05:57 +00004606
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004607 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004608 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004609 else {
4610 RegionCodeGenTy ThenRCG(ThenCodeGen);
4611 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004612 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004613}
4614
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004615void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4616 const OMPLoopDirective &D,
4617 llvm::Value *TaskFunction,
4618 QualType SharedsTy, Address Shareds,
4619 const Expr *IfCond,
4620 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004621 if (!CGF.HaveInsertPoint())
4622 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004623 TaskResultTy Result =
4624 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004625 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4626 // libcall.
4627 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4628 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4629 // sched, kmp_uint64 grainsize, void *task_dup);
4630 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4631 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4632 llvm::Value *IfVal;
4633 if (IfCond) {
4634 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4635 /*isSigned=*/true);
4636 } else
4637 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4638
4639 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004640 Result.TDBase,
4641 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004642 auto *LBVar =
4643 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4644 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4645 /*IsInitializer=*/true);
4646 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004647 Result.TDBase,
4648 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004649 auto *UBVar =
4650 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4651 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4652 /*IsInitializer=*/true);
4653 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004654 Result.TDBase,
4655 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004656 auto *StVar =
4657 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4658 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4659 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004660 // Store reductions address.
4661 LValue RedLVal = CGF.EmitLValueForField(
4662 Result.TDBase,
4663 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4664 if (Data.Reductions)
4665 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4666 else {
4667 CGF.EmitNullInitialization(RedLVal.getAddress(),
4668 CGF.getContext().VoidPtrTy);
4669 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004670 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004671 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004672 UpLoc,
4673 ThreadID,
4674 Result.NewTask,
4675 IfVal,
4676 LBLVal.getPointer(),
4677 UBLVal.getPointer(),
4678 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4679 llvm::ConstantInt::getNullValue(
4680 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004681 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004682 CGF.IntTy, Data.Schedule.getPointer()
4683 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004684 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004685 Data.Schedule.getPointer()
4686 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004687 /*isSigned=*/false)
4688 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004689 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4690 Result.TaskDupFn, CGF.VoidPtrTy)
4691 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004692 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4693}
4694
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004695/// \brief Emit reduction operation for each element of array (required for
4696/// array sections) LHS op = RHS.
4697/// \param Type Type of array.
4698/// \param LHSVar Variable on the left side of the reduction operation
4699/// (references element of array in original variable).
4700/// \param RHSVar Variable on the right side of the reduction operation
4701/// (references element of array in original variable).
4702/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4703/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004704static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004705 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4706 const VarDecl *RHSVar,
4707 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4708 const Expr *, const Expr *)> &RedOpGen,
4709 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4710 const Expr *UpExpr = nullptr) {
4711 // Perform element-by-element initialization.
4712 QualType ElementTy;
4713 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4714 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4715
4716 // Drill down to the base element type on both arrays.
4717 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4718 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4719
4720 auto RHSBegin = RHSAddr.getPointer();
4721 auto LHSBegin = LHSAddr.getPointer();
4722 // Cast from pointer to array type to pointer to single element.
4723 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4724 // The basic structure here is a while-do loop.
4725 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4726 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4727 auto IsEmpty =
4728 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4729 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4730
4731 // Enter the loop body, making that address the current address.
4732 auto EntryBB = CGF.Builder.GetInsertBlock();
4733 CGF.EmitBlock(BodyBB);
4734
4735 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4736
4737 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4738 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4739 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4740 Address RHSElementCurrent =
4741 Address(RHSElementPHI,
4742 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4743
4744 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4745 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4746 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4747 Address LHSElementCurrent =
4748 Address(LHSElementPHI,
4749 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4750
4751 // Emit copy.
4752 CodeGenFunction::OMPPrivateScope Scope(CGF);
4753 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4754 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4755 Scope.Privatize();
4756 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4757 Scope.ForceCleanup();
4758
4759 // Shift the address forward by one element.
4760 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4761 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4762 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4763 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4764 // Check whether we've reached the end.
4765 auto Done =
4766 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4767 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4768 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4769 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4770
4771 // Done.
4772 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4773}
4774
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004775/// Emit reduction combiner. If the combiner is a simple expression emit it as
4776/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4777/// UDR combiner function.
4778static void emitReductionCombiner(CodeGenFunction &CGF,
4779 const Expr *ReductionOp) {
4780 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4781 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4782 if (auto *DRE =
4783 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4784 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4785 std::pair<llvm::Function *, llvm::Function *> Reduction =
4786 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4787 RValue Func = RValue::get(Reduction.first);
4788 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4789 CGF.EmitIgnoredExpr(ReductionOp);
4790 return;
4791 }
4792 CGF.EmitIgnoredExpr(ReductionOp);
4793}
4794
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004795llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4796 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4797 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4798 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004799 auto &C = CGM.getContext();
4800
4801 // void reduction_func(void *LHSArg, void *RHSArg);
4802 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004803 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4804 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004805 Args.push_back(&LHSArg);
4806 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004807 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004808 auto *Fn = llvm::Function::Create(
4809 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4810 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004811 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004812 CodeGenFunction CGF(CGM);
4813 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4814
4815 // Dst = (void*[n])(LHSArg);
4816 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004817 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4818 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4819 ArgsType), CGF.getPointerAlign());
4820 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4821 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4822 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004823
4824 // ...
4825 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4826 // ...
4827 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004828 auto IPriv = Privates.begin();
4829 unsigned Idx = 0;
4830 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004831 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4832 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004833 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004834 });
4835 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4836 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004837 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004838 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004839 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004840 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004841 // Get array size and emit VLA type.
4842 ++Idx;
4843 Address Elem =
4844 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4845 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004846 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4847 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004848 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004849 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004850 CGF.EmitVariablyModifiedType(PrivTy);
4851 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004852 }
4853 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004854 IPriv = Privates.begin();
4855 auto ILHS = LHSExprs.begin();
4856 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004857 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004858 if ((*IPriv)->getType()->isArrayType()) {
4859 // Emit reduction for array section.
4860 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4861 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004862 EmitOMPAggregateReduction(
4863 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4864 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4865 emitReductionCombiner(CGF, E);
4866 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004867 } else
4868 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004869 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004870 ++IPriv;
4871 ++ILHS;
4872 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004873 }
4874 Scope.ForceCleanup();
4875 CGF.FinishFunction();
4876 return Fn;
4877}
4878
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004879void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4880 const Expr *ReductionOp,
4881 const Expr *PrivateRef,
4882 const DeclRefExpr *LHS,
4883 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004884 if (PrivateRef->getType()->isArrayType()) {
4885 // Emit reduction for array section.
4886 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4887 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4888 EmitOMPAggregateReduction(
4889 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4890 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4891 emitReductionCombiner(CGF, ReductionOp);
4892 });
4893 } else
4894 // Emit reduction for array subscript or single variable.
4895 emitReductionCombiner(CGF, ReductionOp);
4896}
4897
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004898void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004899 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004900 ArrayRef<const Expr *> LHSExprs,
4901 ArrayRef<const Expr *> RHSExprs,
4902 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004903 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004904 if (!CGF.HaveInsertPoint())
4905 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004906
4907 bool WithNowait = Options.WithNowait;
4908 bool SimpleReduction = Options.SimpleReduction;
4909
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004910 // Next code should be emitted for reduction:
4911 //
4912 // static kmp_critical_name lock = { 0 };
4913 //
4914 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4915 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4916 // ...
4917 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4918 // *(Type<n>-1*)rhs[<n>-1]);
4919 // }
4920 //
4921 // ...
4922 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4923 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4924 // RedList, reduce_func, &<lock>)) {
4925 // case 1:
4926 // ...
4927 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4928 // ...
4929 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4930 // break;
4931 // case 2:
4932 // ...
4933 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4934 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004935 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004936 // break;
4937 // default:;
4938 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004939 //
4940 // if SimpleReduction is true, only the next code is generated:
4941 // ...
4942 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4943 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004944
4945 auto &C = CGM.getContext();
4946
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004947 if (SimpleReduction) {
4948 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004949 auto IPriv = Privates.begin();
4950 auto ILHS = LHSExprs.begin();
4951 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004952 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004953 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4954 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004955 ++IPriv;
4956 ++ILHS;
4957 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004958 }
4959 return;
4960 }
4961
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004962 // 1. Build a list of reduction variables.
4963 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004964 auto Size = RHSExprs.size();
4965 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004966 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004967 // Reserve place for array size.
4968 ++Size;
4969 }
4970 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004971 QualType ReductionArrayTy =
4972 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4973 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004974 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004975 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004976 auto IPriv = Privates.begin();
4977 unsigned Idx = 0;
4978 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004979 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004980 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004981 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004982 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004983 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4984 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004985 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004986 // Store array size.
4987 ++Idx;
4988 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4989 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004990 llvm::Value *Size = CGF.Builder.CreateIntCast(
4991 CGF.getVLASize(
4992 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4993 .first,
4994 CGF.SizeTy, /*isSigned=*/false);
4995 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4996 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004997 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004998 }
4999
5000 // 2. Emit reduce_func().
5001 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005002 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
5003 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005004
5005 // 3. Create static kmp_critical_name lock = { 0 };
5006 auto *Lock = getCriticalRegionLock(".reduction");
5007
5008 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5009 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005010 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005011 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005012 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005013 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5014 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005015 llvm::Value *Args[] = {
5016 IdentTLoc, // ident_t *<loc>
5017 ThreadId, // i32 <gtid>
5018 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5019 ReductionArrayTySize, // size_type sizeof(RedList)
5020 RL, // void *RedList
5021 ReductionFn, // void (*) (void *, void *) <reduce_func>
5022 Lock // kmp_critical_name *&<lock>
5023 };
5024 auto Res = CGF.EmitRuntimeCall(
5025 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5026 : OMPRTL__kmpc_reduce),
5027 Args);
5028
5029 // 5. Build switch(res)
5030 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5031 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5032
5033 // 6. Build case 1:
5034 // ...
5035 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5036 // ...
5037 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5038 // break;
5039 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5040 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5041 CGF.EmitBlock(Case1BB);
5042
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005043 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5044 llvm::Value *EndArgs[] = {
5045 IdentTLoc, // ident_t *<loc>
5046 ThreadId, // i32 <gtid>
5047 Lock // kmp_critical_name *&<lock>
5048 };
5049 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5050 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005051 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005052 auto IPriv = Privates.begin();
5053 auto ILHS = LHSExprs.begin();
5054 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005055 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005056 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5057 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005058 ++IPriv;
5059 ++ILHS;
5060 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005061 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005062 };
5063 RegionCodeGenTy RCG(CodeGen);
5064 CommonActionTy Action(
5065 nullptr, llvm::None,
5066 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5067 : OMPRTL__kmpc_end_reduce),
5068 EndArgs);
5069 RCG.setAction(Action);
5070 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005071
5072 CGF.EmitBranch(DefaultBB);
5073
5074 // 7. Build case 2:
5075 // ...
5076 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5077 // ...
5078 // break;
5079 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5080 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5081 CGF.EmitBlock(Case2BB);
5082
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005083 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5084 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005085 auto ILHS = LHSExprs.begin();
5086 auto IRHS = RHSExprs.begin();
5087 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005088 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005089 const Expr *XExpr = nullptr;
5090 const Expr *EExpr = nullptr;
5091 const Expr *UpExpr = nullptr;
5092 BinaryOperatorKind BO = BO_Comma;
5093 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5094 if (BO->getOpcode() == BO_Assign) {
5095 XExpr = BO->getLHS();
5096 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005097 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005098 }
5099 // Try to emit update expression as a simple atomic.
5100 auto *RHSExpr = UpExpr;
5101 if (RHSExpr) {
5102 // Analyze RHS part of the whole expression.
5103 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5104 RHSExpr->IgnoreParenImpCasts())) {
5105 // If this is a conditional operator, analyze its condition for
5106 // min/max reduction operator.
5107 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005108 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005109 if (auto *BORHS =
5110 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5111 EExpr = BORHS->getRHS();
5112 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005113 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005114 }
5115 if (XExpr) {
5116 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005117 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005118 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5119 const Expr *EExpr, const Expr *UpExpr) {
5120 LValue X = CGF.EmitLValue(XExpr);
5121 RValue E;
5122 if (EExpr)
5123 E = CGF.EmitAnyExpr(EExpr);
5124 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005125 X, E, BO, /*IsXLHSInRHSPart=*/true,
5126 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005127 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005128 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5129 PrivateScope.addPrivate(
5130 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5131 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5132 CGF.emitOMPSimpleStore(
5133 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5134 VD->getType().getNonReferenceType(), Loc);
5135 return LHSTemp;
5136 });
5137 (void)PrivateScope.Privatize();
5138 return CGF.EmitAnyExpr(UpExpr);
5139 });
5140 };
5141 if ((*IPriv)->getType()->isArrayType()) {
5142 // Emit atomic reduction for array section.
5143 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5144 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5145 AtomicRedGen, XExpr, EExpr, UpExpr);
5146 } else
5147 // Emit atomic reduction for array subscript or single variable.
5148 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5149 } else {
5150 // Emit as a critical region.
5151 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5152 const Expr *, const Expr *) {
5153 auto &RT = CGF.CGM.getOpenMPRuntime();
5154 RT.emitCriticalRegion(
5155 CGF, ".atomic_reduction",
5156 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5157 Action.Enter(CGF);
5158 emitReductionCombiner(CGF, E);
5159 },
5160 Loc);
5161 };
5162 if ((*IPriv)->getType()->isArrayType()) {
5163 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5164 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5165 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5166 CritRedGen);
5167 } else
5168 CritRedGen(CGF, nullptr, nullptr, nullptr);
5169 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005170 ++ILHS;
5171 ++IRHS;
5172 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005173 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005174 };
5175 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5176 if (!WithNowait) {
5177 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5178 llvm::Value *EndArgs[] = {
5179 IdentTLoc, // ident_t *<loc>
5180 ThreadId, // i32 <gtid>
5181 Lock // kmp_critical_name *&<lock>
5182 };
5183 CommonActionTy Action(nullptr, llvm::None,
5184 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5185 EndArgs);
5186 AtomicRCG.setAction(Action);
5187 AtomicRCG(CGF);
5188 } else
5189 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005190
5191 CGF.EmitBranch(DefaultBB);
5192 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5193}
5194
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005195/// Generates unique name for artificial threadprivate variables.
5196/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5197static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5198 unsigned N) {
5199 SmallString<256> Buffer;
5200 llvm::raw_svector_ostream Out(Buffer);
5201 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5202 return Out.str();
5203}
5204
5205/// Emits reduction initializer function:
5206/// \code
5207/// void @.red_init(void* %arg) {
5208/// %0 = bitcast void* %arg to <type>*
5209/// store <type> <init>, <type>* %0
5210/// ret void
5211/// }
5212/// \endcode
5213static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5214 SourceLocation Loc,
5215 ReductionCodeGen &RCG, unsigned N) {
5216 auto &C = CGM.getContext();
5217 FunctionArgList Args;
5218 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5219 Args.emplace_back(&Param);
5220 auto &FnInfo =
5221 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5222 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5223 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5224 ".red_init.", &CGM.getModule());
5225 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5226 CodeGenFunction CGF(CGM);
5227 CGF.disableDebugInfo();
5228 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5229 Address PrivateAddr = CGF.EmitLoadOfPointer(
5230 CGF.GetAddrOfLocalVar(&Param),
5231 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5232 llvm::Value *Size = nullptr;
5233 // If the size of the reduction item is non-constant, load it from global
5234 // threadprivate variable.
5235 if (RCG.getSizes(N).second) {
5236 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5237 CGF, CGM.getContext().getSizeType(),
5238 generateUniqueName("reduction_size", Loc, N));
5239 Size =
5240 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5241 CGM.getContext().getSizeType(), SourceLocation());
5242 }
5243 RCG.emitAggregateType(CGF, N, Size);
5244 LValue SharedLVal;
5245 // If initializer uses initializer from declare reduction construct, emit a
5246 // pointer to the address of the original reduction item (reuired by reduction
5247 // initializer)
5248 if (RCG.usesReductionInitializer(N)) {
5249 Address SharedAddr =
5250 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5251 CGF, CGM.getContext().VoidPtrTy,
5252 generateUniqueName("reduction", Loc, N));
5253 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5254 } else {
5255 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5256 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5257 CGM.getContext().VoidPtrTy);
5258 }
5259 // Emit the initializer:
5260 // %0 = bitcast void* %arg to <type>*
5261 // store <type> <init>, <type>* %0
5262 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5263 [](CodeGenFunction &) { return false; });
5264 CGF.FinishFunction();
5265 return Fn;
5266}
5267
5268/// Emits reduction combiner function:
5269/// \code
5270/// void @.red_comb(void* %arg0, void* %arg1) {
5271/// %lhs = bitcast void* %arg0 to <type>*
5272/// %rhs = bitcast void* %arg1 to <type>*
5273/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5274/// store <type> %2, <type>* %lhs
5275/// ret void
5276/// }
5277/// \endcode
5278static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5279 SourceLocation Loc,
5280 ReductionCodeGen &RCG, unsigned N,
5281 const Expr *ReductionOp,
5282 const Expr *LHS, const Expr *RHS,
5283 const Expr *PrivateRef) {
5284 auto &C = CGM.getContext();
5285 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5286 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5287 FunctionArgList Args;
5288 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5289 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5290 Args.emplace_back(&ParamInOut);
5291 Args.emplace_back(&ParamIn);
5292 auto &FnInfo =
5293 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5294 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5295 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5296 ".red_comb.", &CGM.getModule());
5297 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5298 CodeGenFunction CGF(CGM);
5299 CGF.disableDebugInfo();
5300 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5301 llvm::Value *Size = nullptr;
5302 // If the size of the reduction item is non-constant, load it from global
5303 // threadprivate variable.
5304 if (RCG.getSizes(N).second) {
5305 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5306 CGF, CGM.getContext().getSizeType(),
5307 generateUniqueName("reduction_size", Loc, N));
5308 Size =
5309 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5310 CGM.getContext().getSizeType(), SourceLocation());
5311 }
5312 RCG.emitAggregateType(CGF, N, Size);
5313 // Remap lhs and rhs variables to the addresses of the function arguments.
5314 // %lhs = bitcast void* %arg0 to <type>*
5315 // %rhs = bitcast void* %arg1 to <type>*
5316 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5317 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5318 // Pull out the pointer to the variable.
5319 Address PtrAddr = CGF.EmitLoadOfPointer(
5320 CGF.GetAddrOfLocalVar(&ParamInOut),
5321 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5322 return CGF.Builder.CreateElementBitCast(
5323 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5324 });
5325 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5326 // Pull out the pointer to the variable.
5327 Address PtrAddr = CGF.EmitLoadOfPointer(
5328 CGF.GetAddrOfLocalVar(&ParamIn),
5329 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5330 return CGF.Builder.CreateElementBitCast(
5331 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5332 });
5333 PrivateScope.Privatize();
5334 // Emit the combiner body:
5335 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5336 // store <type> %2, <type>* %lhs
5337 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5338 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5339 cast<DeclRefExpr>(RHS));
5340 CGF.FinishFunction();
5341 return Fn;
5342}
5343
5344/// Emits reduction finalizer function:
5345/// \code
5346/// void @.red_fini(void* %arg) {
5347/// %0 = bitcast void* %arg to <type>*
5348/// <destroy>(<type>* %0)
5349/// ret void
5350/// }
5351/// \endcode
5352static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5353 SourceLocation Loc,
5354 ReductionCodeGen &RCG, unsigned N) {
5355 if (!RCG.needCleanups(N))
5356 return nullptr;
5357 auto &C = CGM.getContext();
5358 FunctionArgList Args;
5359 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5360 Args.emplace_back(&Param);
5361 auto &FnInfo =
5362 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5363 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5364 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5365 ".red_fini.", &CGM.getModule());
5366 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5367 CodeGenFunction CGF(CGM);
5368 CGF.disableDebugInfo();
5369 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5370 Address PrivateAddr = CGF.EmitLoadOfPointer(
5371 CGF.GetAddrOfLocalVar(&Param),
5372 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5373 llvm::Value *Size = nullptr;
5374 // If the size of the reduction item is non-constant, load it from global
5375 // threadprivate variable.
5376 if (RCG.getSizes(N).second) {
5377 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5378 CGF, CGM.getContext().getSizeType(),
5379 generateUniqueName("reduction_size", Loc, N));
5380 Size =
5381 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5382 CGM.getContext().getSizeType(), SourceLocation());
5383 }
5384 RCG.emitAggregateType(CGF, N, Size);
5385 // Emit the finalizer body:
5386 // <destroy>(<type>* %0)
5387 RCG.emitCleanups(CGF, N, PrivateAddr);
5388 CGF.FinishFunction();
5389 return Fn;
5390}
5391
5392llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5393 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5394 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5395 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5396 return nullptr;
5397
5398 // Build typedef struct:
5399 // kmp_task_red_input {
5400 // void *reduce_shar; // shared reduction item
5401 // size_t reduce_size; // size of data item
5402 // void *reduce_init; // data initialization routine
5403 // void *reduce_fini; // data finalization routine
5404 // void *reduce_comb; // data combiner routine
5405 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5406 // } kmp_task_red_input_t;
5407 ASTContext &C = CGM.getContext();
5408 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5409 RD->startDefinition();
5410 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5411 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5412 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5413 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5414 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5415 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5416 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5417 RD->completeDefinition();
5418 QualType RDType = C.getRecordType(RD);
5419 unsigned Size = Data.ReductionVars.size();
5420 llvm::APInt ArraySize(/*numBits=*/64, Size);
5421 QualType ArrayRDType = C.getConstantArrayType(
5422 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5423 // kmp_task_red_input_t .rd_input.[Size];
5424 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5425 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5426 Data.ReductionOps);
5427 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5428 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5429 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5430 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5431 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5432 TaskRedInput.getPointer(), Idxs,
5433 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5434 ".rd_input.gep.");
5435 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5436 // ElemLVal.reduce_shar = &Shareds[Cnt];
5437 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5438 RCG.emitSharedLValue(CGF, Cnt);
5439 llvm::Value *CastedShared =
5440 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5441 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5442 RCG.emitAggregateType(CGF, Cnt);
5443 llvm::Value *SizeValInChars;
5444 llvm::Value *SizeVal;
5445 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5446 // We use delayed creation/initialization for VLAs, array sections and
5447 // custom reduction initializations. It is required because runtime does not
5448 // provide the way to pass the sizes of VLAs/array sections to
5449 // initializer/combiner/finalizer functions and does not pass the pointer to
5450 // original reduction item to the initializer. Instead threadprivate global
5451 // variables are used to store these values and use them in the functions.
5452 bool DelayedCreation = !!SizeVal;
5453 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5454 /*isSigned=*/false);
5455 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5456 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5457 // ElemLVal.reduce_init = init;
5458 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5459 llvm::Value *InitAddr =
5460 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5461 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5462 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5463 // ElemLVal.reduce_fini = fini;
5464 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5465 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5466 llvm::Value *FiniAddr = Fini
5467 ? CGF.EmitCastToVoidPtr(Fini)
5468 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5469 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5470 // ElemLVal.reduce_comb = comb;
5471 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5472 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5473 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5474 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5475 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5476 // ElemLVal.flags = 0;
5477 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5478 if (DelayedCreation) {
5479 CGF.EmitStoreOfScalar(
5480 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5481 FlagsLVal);
5482 } else
5483 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5484 }
5485 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5486 // *data);
5487 llvm::Value *Args[] = {
5488 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5489 /*isSigned=*/true),
5490 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5491 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5492 CGM.VoidPtrTy)};
5493 return CGF.EmitRuntimeCall(
5494 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5495}
5496
5497void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5498 SourceLocation Loc,
5499 ReductionCodeGen &RCG,
5500 unsigned N) {
5501 auto Sizes = RCG.getSizes(N);
5502 // Emit threadprivate global variable if the type is non-constant
5503 // (Sizes.second = nullptr).
5504 if (Sizes.second) {
5505 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5506 /*isSigned=*/false);
5507 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5508 CGF, CGM.getContext().getSizeType(),
5509 generateUniqueName("reduction_size", Loc, N));
5510 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5511 }
5512 // Store address of the original reduction item if custom initializer is used.
5513 if (RCG.usesReductionInitializer(N)) {
5514 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5515 CGF, CGM.getContext().VoidPtrTy,
5516 generateUniqueName("reduction", Loc, N));
5517 CGF.Builder.CreateStore(
5518 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5519 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5520 SharedAddr, /*IsVolatile=*/false);
5521 }
5522}
5523
5524Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5525 SourceLocation Loc,
5526 llvm::Value *ReductionsPtr,
5527 LValue SharedLVal) {
5528 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5529 // *d);
5530 llvm::Value *Args[] = {
5531 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5532 /*isSigned=*/true),
5533 ReductionsPtr,
5534 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5535 CGM.VoidPtrTy)};
5536 return Address(
5537 CGF.EmitRuntimeCall(
5538 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5539 SharedLVal.getAlignment());
5540}
5541
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005542void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5543 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005544 if (!CGF.HaveInsertPoint())
5545 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005546 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5547 // global_tid);
5548 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5549 // Ignore return result until untied tasks are supported.
5550 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005551 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5552 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005553}
5554
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005555void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005556 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005557 const RegionCodeGenTy &CodeGen,
5558 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005559 if (!CGF.HaveInsertPoint())
5560 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005561 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005562 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005563}
5564
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005565namespace {
5566enum RTCancelKind {
5567 CancelNoreq = 0,
5568 CancelParallel = 1,
5569 CancelLoop = 2,
5570 CancelSections = 3,
5571 CancelTaskgroup = 4
5572};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005573} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005574
5575static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5576 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005577 if (CancelRegion == OMPD_parallel)
5578 CancelKind = CancelParallel;
5579 else if (CancelRegion == OMPD_for)
5580 CancelKind = CancelLoop;
5581 else if (CancelRegion == OMPD_sections)
5582 CancelKind = CancelSections;
5583 else {
5584 assert(CancelRegion == OMPD_taskgroup);
5585 CancelKind = CancelTaskgroup;
5586 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005587 return CancelKind;
5588}
5589
5590void CGOpenMPRuntime::emitCancellationPointCall(
5591 CodeGenFunction &CGF, SourceLocation Loc,
5592 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005593 if (!CGF.HaveInsertPoint())
5594 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005595 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5596 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005597 if (auto *OMPRegionInfo =
5598 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005599 // For 'cancellation point taskgroup', the task region info may not have a
5600 // cancel. This may instead happen in another adjacent task.
5601 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005602 llvm::Value *Args[] = {
5603 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5604 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005605 // Ignore return result until untied tasks are supported.
5606 auto *Result = CGF.EmitRuntimeCall(
5607 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5608 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005609 // exit from construct;
5610 // }
5611 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5612 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5613 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5614 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5615 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005616 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005617 auto CancelDest =
5618 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005619 CGF.EmitBranchThroughCleanup(CancelDest);
5620 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5621 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005622 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005623}
5624
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005625void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005626 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005627 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005628 if (!CGF.HaveInsertPoint())
5629 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005630 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5631 // kmp_int32 cncl_kind);
5632 if (auto *OMPRegionInfo =
5633 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005634 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5635 PrePostActionTy &) {
5636 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005637 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005638 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005639 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5640 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005641 auto *Result = CGF.EmitRuntimeCall(
5642 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005643 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005644 // exit from construct;
5645 // }
5646 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5647 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5648 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5649 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5650 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005651 // exit from construct;
5652 auto CancelDest =
5653 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5654 CGF.EmitBranchThroughCleanup(CancelDest);
5655 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5656 };
5657 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005658 emitOMPIfClause(CGF, IfCond, ThenGen,
5659 [](CodeGenFunction &, PrePostActionTy &) {});
5660 else {
5661 RegionCodeGenTy ThenRCG(ThenGen);
5662 ThenRCG(CGF);
5663 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005664 }
5665}
Samuel Antaobed3c462015-10-02 16:14:20 +00005666
Samuel Antaoee8fb302016-01-06 13:42:12 +00005667/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005668/// consists of the file and device IDs as well as line number associated with
5669/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005670static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5671 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005672 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005673
5674 auto &SM = C.getSourceManager();
5675
5676 // The loc should be always valid and have a file ID (the user cannot use
5677 // #pragma directives in macros)
5678
5679 assert(Loc.isValid() && "Source location is expected to be always valid.");
5680 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5681
5682 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5683 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5684
5685 llvm::sys::fs::UniqueID ID;
5686 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5687 llvm_unreachable("Source file with target region no longer exists!");
5688
5689 DeviceID = ID.getDevice();
5690 FileID = ID.getFile();
5691 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005692}
5693
5694void CGOpenMPRuntime::emitTargetOutlinedFunction(
5695 const OMPExecutableDirective &D, StringRef ParentName,
5696 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005697 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005698 assert(!ParentName.empty() && "Invalid target region parent name!");
5699
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005700 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5701 IsOffloadEntry, CodeGen);
5702}
5703
5704void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5705 const OMPExecutableDirective &D, StringRef ParentName,
5706 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5707 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005708 // Create a unique name for the entry function using the source location
5709 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005710 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005711 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005712 //
5713 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005714 // mangled name of the function that encloses the target region and BB is the
5715 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005716
5717 unsigned DeviceID;
5718 unsigned FileID;
5719 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005720 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005721 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005722 SmallString<64> EntryFnName;
5723 {
5724 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005725 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5726 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005727 }
5728
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005729 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5730
Samuel Antaobed3c462015-10-02 16:14:20 +00005731 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005732 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005733 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005734
Samuel Antao6d004262016-06-16 18:39:34 +00005735 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005736
5737 // If this target outline function is not an offload entry, we don't need to
5738 // register it.
5739 if (!IsOffloadEntry)
5740 return;
5741
5742 // The target region ID is used by the runtime library to identify the current
5743 // target region, so it only has to be unique and not necessarily point to
5744 // anything. It could be the pointer to the outlined function that implements
5745 // the target region, but we aren't using that so that the compiler doesn't
5746 // need to keep that, and could therefore inline the host function if proven
5747 // worthwhile during optimization. In the other hand, if emitting code for the
5748 // device, the ID has to be the function address so that it can retrieved from
5749 // the offloading entry and launched by the runtime library. We also mark the
5750 // outlined function to have external linkage in case we are emitting code for
5751 // the device, because these functions will be entry points to the device.
5752
5753 if (CGM.getLangOpts().OpenMPIsDevice) {
5754 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5755 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5756 } else
5757 OutlinedFnID = new llvm::GlobalVariable(
5758 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5759 llvm::GlobalValue::PrivateLinkage,
5760 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5761
5762 // Register the information for the entry associated with this target region.
5763 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005764 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5765 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005766}
5767
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005768/// discard all CompoundStmts intervening between two constructs
5769static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5770 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5771 Body = CS->body_front();
5772
5773 return Body;
5774}
5775
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005776/// Emit the number of teams for a target directive. Inspect the num_teams
5777/// clause associated with a teams construct combined or closely nested
5778/// with the target directive.
5779///
5780/// Emit a team of size one for directives such as 'target parallel' that
5781/// have no associated teams construct.
5782///
5783/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005784static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005785emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5786 CodeGenFunction &CGF,
5787 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005788
5789 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5790 "teams directive expected to be "
5791 "emitted only for the host!");
5792
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005793 auto &Bld = CGF.Builder;
5794
5795 // If the target directive is combined with a teams directive:
5796 // Return the value in the num_teams clause, if any.
5797 // Otherwise, return 0 to denote the runtime default.
5798 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5799 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5800 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5801 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5802 /*IgnoreResultAssign*/ true);
5803 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5804 /*IsSigned=*/true);
5805 }
5806
5807 // The default value is 0.
5808 return Bld.getInt32(0);
5809 }
5810
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005811 // If the target directive is combined with a parallel directive but not a
5812 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005813 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5814 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005815
5816 // If the current target region has a teams region enclosed, we need to get
5817 // the number of teams to pass to the runtime function call. This is done
5818 // by generating the expression in a inlined region. This is required because
5819 // the expression is captured in the enclosing target environment when the
5820 // teams directive is not combined with target.
5821
5822 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5823
5824 // FIXME: Accommodate other combined directives with teams when they become
5825 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005826 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5827 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005828 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5829 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5830 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5831 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005832 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5833 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005834 }
5835
5836 // If we have an enclosed teams directive but no num_teams clause we use
5837 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005838 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005839 }
5840
5841 // No teams associated with the directive.
5842 return nullptr;
5843}
5844
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005845/// Emit the number of threads for a target directive. Inspect the
5846/// thread_limit clause associated with a teams construct combined or closely
5847/// nested with the target directive.
5848///
5849/// Emit the num_threads clause for directives such as 'target parallel' that
5850/// have no associated teams construct.
5851///
5852/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005853static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005854emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5855 CodeGenFunction &CGF,
5856 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005857
5858 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5859 "teams directive expected to be "
5860 "emitted only for the host!");
5861
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005862 auto &Bld = CGF.Builder;
5863
5864 //
5865 // If the target directive is combined with a teams directive:
5866 // Return the value in the thread_limit clause, if any.
5867 //
5868 // If the target directive is combined with a parallel directive:
5869 // Return the value in the num_threads clause, if any.
5870 //
5871 // If both clauses are set, select the minimum of the two.
5872 //
5873 // If neither teams or parallel combined directives set the number of threads
5874 // in a team, return 0 to denote the runtime default.
5875 //
5876 // If this is not a teams directive return nullptr.
5877
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005878 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5879 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005880 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5881 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005882 llvm::Value *ThreadLimitVal = nullptr;
5883
5884 if (const auto *ThreadLimitClause =
5885 D.getSingleClause<OMPThreadLimitClause>()) {
5886 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5887 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5888 /*IgnoreResultAssign*/ true);
5889 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5890 /*IsSigned=*/true);
5891 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005892
5893 if (const auto *NumThreadsClause =
5894 D.getSingleClause<OMPNumThreadsClause>()) {
5895 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5896 llvm::Value *NumThreads =
5897 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5898 /*IgnoreResultAssign*/ true);
5899 NumThreadsVal =
5900 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5901 }
5902
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005903 // Select the lesser of thread_limit and num_threads.
5904 if (NumThreadsVal)
5905 ThreadLimitVal = ThreadLimitVal
5906 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5907 ThreadLimitVal),
5908 NumThreadsVal, ThreadLimitVal)
5909 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005910
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005911 // Set default value passed to the runtime if either teams or a target
5912 // parallel type directive is found but no clause is specified.
5913 if (!ThreadLimitVal)
5914 ThreadLimitVal = DefaultThreadLimitVal;
5915
5916 return ThreadLimitVal;
5917 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005918
Samuel Antaob68e2db2016-03-03 16:20:23 +00005919 // If the current target region has a teams region enclosed, we need to get
5920 // the thread limit to pass to the runtime function call. This is done
5921 // by generating the expression in a inlined region. This is required because
5922 // the expression is captured in the enclosing target environment when the
5923 // teams directive is not combined with target.
5924
5925 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5926
5927 // FIXME: Accommodate other combined directives with teams when they become
5928 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005929 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5930 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005931 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5932 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5933 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5934 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5935 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5936 /*IsSigned=*/true);
5937 }
5938
5939 // If we have an enclosed teams directive but no thread_limit clause we use
5940 // the default value 0.
5941 return CGF.Builder.getInt32(0);
5942 }
5943
5944 // No teams associated with the directive.
5945 return nullptr;
5946}
5947
Samuel Antao86ace552016-04-27 22:40:57 +00005948namespace {
5949// \brief Utility to handle information from clauses associated with a given
5950// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5951// It provides a convenient interface to obtain the information and generate
5952// code for that information.
5953class MappableExprsHandler {
5954public:
5955 /// \brief Values for bit flags used to specify the mapping type for
5956 /// offloading.
5957 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005958 /// \brief Allocate memory on the device and move data from host to device.
5959 OMP_MAP_TO = 0x01,
5960 /// \brief Allocate memory on the device and move data from device to host.
5961 OMP_MAP_FROM = 0x02,
5962 /// \brief Always perform the requested mapping action on the element, even
5963 /// if it was already mapped before.
5964 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005965 /// \brief Delete the element from the device environment, ignoring the
5966 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005967 OMP_MAP_DELETE = 0x08,
5968 /// \brief The element being mapped is a pointer, therefore the pointee
5969 /// should be mapped as well.
5970 OMP_MAP_IS_PTR = 0x10,
5971 /// \brief This flags signals that an argument is the first one relating to
5972 /// a map/private clause expression. For some cases a single
5973 /// map/privatization results in multiple arguments passed to the runtime
5974 /// library.
5975 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005976 /// \brief Signal that the runtime library has to return the device pointer
5977 /// in the current position for the data being mapped.
5978 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005979 /// \brief This flag signals that the reference being passed is a pointer to
5980 /// private data.
5981 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005982 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005983 OMP_MAP_PRIVATE_VAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00005984 /// Implicit map
5985 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00005986 };
5987
Samuel Antaocc10b852016-07-28 14:23:26 +00005988 /// Class that associates information with a base pointer to be passed to the
5989 /// runtime library.
5990 class BasePointerInfo {
5991 /// The base pointer.
5992 llvm::Value *Ptr = nullptr;
5993 /// The base declaration that refers to this device pointer, or null if
5994 /// there is none.
5995 const ValueDecl *DevPtrDecl = nullptr;
5996
5997 public:
5998 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5999 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6000 llvm::Value *operator*() const { return Ptr; }
6001 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6002 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6003 };
6004
6005 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006006 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
6007 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
6008
6009private:
6010 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006011 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006012
6013 /// \brief Function the directive is being generated for.
6014 CodeGenFunction &CGF;
6015
Samuel Antaod486f842016-05-26 16:53:38 +00006016 /// \brief Set of all first private variables in the current directive.
6017 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6018
Samuel Antao6890b092016-07-28 14:25:09 +00006019 /// Map between device pointer declarations and their expression components.
6020 /// The key value for declarations in 'this' is null.
6021 llvm::DenseMap<
6022 const ValueDecl *,
6023 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6024 DevPointersMap;
6025
Samuel Antao86ace552016-04-27 22:40:57 +00006026 llvm::Value *getExprTypeSize(const Expr *E) const {
6027 auto ExprTy = E->getType().getCanonicalType();
6028
6029 // Reference types are ignored for mapping purposes.
6030 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6031 ExprTy = RefTy->getPointeeType().getCanonicalType();
6032
6033 // Given that an array section is considered a built-in type, we need to
6034 // do the calculation based on the length of the section instead of relying
6035 // on CGF.getTypeSize(E->getType()).
6036 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6037 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6038 OAE->getBase()->IgnoreParenImpCasts())
6039 .getCanonicalType();
6040
6041 // If there is no length associated with the expression, that means we
6042 // are using the whole length of the base.
6043 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6044 return CGF.getTypeSize(BaseTy);
6045
6046 llvm::Value *ElemSize;
6047 if (auto *PTy = BaseTy->getAs<PointerType>())
6048 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6049 else {
6050 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6051 assert(ATy && "Expecting array type if not a pointer type.");
6052 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6053 }
6054
6055 // If we don't have a length at this point, that is because we have an
6056 // array section with a single element.
6057 if (!OAE->getLength())
6058 return ElemSize;
6059
6060 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6061 LengthVal =
6062 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6063 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6064 }
6065 return CGF.getTypeSize(ExprTy);
6066 }
6067
6068 /// \brief Return the corresponding bits for a given map clause modifier. Add
6069 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006070 /// map as the first one of a series of maps that relate to the same map
6071 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00006072 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6073 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00006074 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006075 unsigned Bits = 0u;
6076 switch (MapType) {
6077 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006078 case OMPC_MAP_release:
6079 // alloc and release is the default behavior in the runtime library, i.e.
6080 // if we don't pass any bits alloc/release that is what the runtime is
6081 // going to do. Therefore, we don't need to signal anything for these two
6082 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006083 break;
6084 case OMPC_MAP_to:
6085 Bits = OMP_MAP_TO;
6086 break;
6087 case OMPC_MAP_from:
6088 Bits = OMP_MAP_FROM;
6089 break;
6090 case OMPC_MAP_tofrom:
6091 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6092 break;
6093 case OMPC_MAP_delete:
6094 Bits = OMP_MAP_DELETE;
6095 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006096 default:
6097 llvm_unreachable("Unexpected map type!");
6098 break;
6099 }
6100 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00006101 Bits |= OMP_MAP_IS_PTR;
6102 if (AddIsFirstFlag)
6103 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00006104 if (MapTypeModifier == OMPC_MAP_always)
6105 Bits |= OMP_MAP_ALWAYS;
6106 return Bits;
6107 }
6108
6109 /// \brief Return true if the provided expression is a final array section. A
6110 /// final array section, is one whose length can't be proved to be one.
6111 bool isFinalArraySectionExpression(const Expr *E) const {
6112 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6113
6114 // It is not an array section and therefore not a unity-size one.
6115 if (!OASE)
6116 return false;
6117
6118 // An array section with no colon always refer to a single element.
6119 if (OASE->getColonLoc().isInvalid())
6120 return false;
6121
6122 auto *Length = OASE->getLength();
6123
6124 // If we don't have a length we have to check if the array has size 1
6125 // for this dimension. Also, we should always expect a length if the
6126 // base type is pointer.
6127 if (!Length) {
6128 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6129 OASE->getBase()->IgnoreParenImpCasts())
6130 .getCanonicalType();
6131 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6132 return ATy->getSize().getSExtValue() != 1;
6133 // If we don't have a constant dimension length, we have to consider
6134 // the current section as having any size, so it is not necessarily
6135 // unitary. If it happen to be unity size, that's user fault.
6136 return true;
6137 }
6138
6139 // Check if the length evaluates to 1.
6140 llvm::APSInt ConstLength;
6141 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6142 return true; // Can have more that size 1.
6143
6144 return ConstLength.getSExtValue() != 1;
6145 }
6146
6147 /// \brief Generate the base pointers, section pointers, sizes and map type
6148 /// bits for the provided map type, map modifier, and expression components.
6149 /// \a IsFirstComponent should be set to true if the provided set of
6150 /// components is the first associated with a capture.
6151 void generateInfoForComponentList(
6152 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6153 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006154 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006155 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006156 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006157
6158 // The following summarizes what has to be generated for each map and the
6159 // types bellow. The generated information is expressed in this order:
6160 // base pointer, section pointer, size, flags
6161 // (to add to the ones that come from the map type and modifier).
6162 //
6163 // double d;
6164 // int i[100];
6165 // float *p;
6166 //
6167 // struct S1 {
6168 // int i;
6169 // float f[50];
6170 // }
6171 // struct S2 {
6172 // int i;
6173 // float f[50];
6174 // S1 s;
6175 // double *p;
6176 // struct S2 *ps;
6177 // }
6178 // S2 s;
6179 // S2 *ps;
6180 //
6181 // map(d)
6182 // &d, &d, sizeof(double), noflags
6183 //
6184 // map(i)
6185 // &i, &i, 100*sizeof(int), noflags
6186 //
6187 // map(i[1:23])
6188 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6189 //
6190 // map(p)
6191 // &p, &p, sizeof(float*), noflags
6192 //
6193 // map(p[1:24])
6194 // p, &p[1], 24*sizeof(float), noflags
6195 //
6196 // map(s)
6197 // &s, &s, sizeof(S2), noflags
6198 //
6199 // map(s.i)
6200 // &s, &(s.i), sizeof(int), noflags
6201 //
6202 // map(s.s.f)
6203 // &s, &(s.i.f), 50*sizeof(int), noflags
6204 //
6205 // map(s.p)
6206 // &s, &(s.p), sizeof(double*), noflags
6207 //
6208 // map(s.p[:22], s.a s.b)
6209 // &s, &(s.p), sizeof(double*), noflags
6210 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
6211 //
6212 // map(s.ps)
6213 // &s, &(s.ps), sizeof(S2*), noflags
6214 //
6215 // map(s.ps->s.i)
6216 // &s, &(s.ps), sizeof(S2*), noflags
6217 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
6218 //
6219 // map(s.ps->ps)
6220 // &s, &(s.ps), sizeof(S2*), noflags
6221 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6222 //
6223 // map(s.ps->ps->ps)
6224 // &s, &(s.ps), sizeof(S2*), noflags
6225 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6226 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6227 //
6228 // map(s.ps->ps->s.f[:22])
6229 // &s, &(s.ps), sizeof(S2*), noflags
6230 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6231 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
6232 //
6233 // map(ps)
6234 // &ps, &ps, sizeof(S2*), noflags
6235 //
6236 // map(ps->i)
6237 // ps, &(ps->i), sizeof(int), noflags
6238 //
6239 // map(ps->s.f)
6240 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6241 //
6242 // map(ps->p)
6243 // ps, &(ps->p), sizeof(double*), noflags
6244 //
6245 // map(ps->p[:22])
6246 // ps, &(ps->p), sizeof(double*), noflags
6247 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
6248 //
6249 // map(ps->ps)
6250 // ps, &(ps->ps), sizeof(S2*), noflags
6251 //
6252 // map(ps->ps->s.i)
6253 // ps, &(ps->ps), sizeof(S2*), noflags
6254 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
6255 //
6256 // map(ps->ps->ps)
6257 // ps, &(ps->ps), sizeof(S2*), noflags
6258 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6259 //
6260 // map(ps->ps->ps->ps)
6261 // ps, &(ps->ps), sizeof(S2*), noflags
6262 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6263 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6264 //
6265 // map(ps->ps->ps->s.f[:22])
6266 // ps, &(ps->ps), sizeof(S2*), noflags
6267 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6268 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
6269 // extra_flag
6270
6271 // Track if the map information being generated is the first for a capture.
6272 bool IsCaptureFirstInfo = IsFirstComponentList;
6273
6274 // Scan the components from the base to the complete expression.
6275 auto CI = Components.rbegin();
6276 auto CE = Components.rend();
6277 auto I = CI;
6278
6279 // Track if the map information being generated is the first for a list of
6280 // components.
6281 bool IsExpressionFirstInfo = true;
6282 llvm::Value *BP = nullptr;
6283
6284 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6285 // The base is the 'this' pointer. The content of the pointer is going
6286 // to be the base of the field being mapped.
6287 BP = CGF.EmitScalarExpr(ME->getBase());
6288 } else {
6289 // The base is the reference to the variable.
6290 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006291 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006292
6293 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006294 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006295 // reference. References are ignored for mapping purposes.
6296 QualType Ty =
6297 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6298 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6299 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006300 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006301 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006302 .getPointer();
6303
6304 // We do not need to generate individual map information for the
6305 // pointer, it can be associated with the combined storage.
6306 ++I;
6307 }
6308 }
6309
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006310 unsigned DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006311 for (; I != CE; ++I) {
6312 auto Next = std::next(I);
6313
6314 // We need to generate the addresses and sizes if this is the last
6315 // component, if the component is a pointer or if it is an array section
6316 // whose length can't be proved to be one. If this is a pointer, it
6317 // becomes the base address for the following components.
6318
6319 // A final array section, is one whose length can't be proved to be one.
6320 bool IsFinalArraySection =
6321 isFinalArraySectionExpression(I->getAssociatedExpression());
6322
6323 // Get information on whether the element is a pointer. Have to do a
6324 // special treatment for array sections given that they are built-in
6325 // types.
6326 const auto *OASE =
6327 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6328 bool IsPointer =
6329 (OASE &&
6330 OMPArraySectionExpr::getBaseOriginalType(OASE)
6331 .getCanonicalType()
6332 ->isAnyPointerType()) ||
6333 I->getAssociatedExpression()->getType()->isAnyPointerType();
6334
6335 if (Next == CE || IsPointer || IsFinalArraySection) {
6336
6337 // If this is not the last component, we expect the pointer to be
6338 // associated with an array expression or member expression.
6339 assert((Next == CE ||
6340 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6341 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6342 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6343 "Unexpected expression");
6344
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006345 llvm::Value *LB =
6346 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006347 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6348
Samuel Antao03a3cec2016-07-27 22:52:16 +00006349 // If we have a member expression and the current component is a
6350 // reference, we have to map the reference too. Whenever we have a
6351 // reference, the section that reference refers to is going to be a
6352 // load instruction from the storage assigned to the reference.
6353 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6354 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6355 auto *LI = cast<llvm::LoadInst>(LB);
6356 auto *RefAddr = LI->getPointerOperand();
6357
6358 BasePointers.push_back(BP);
6359 Pointers.push_back(RefAddr);
6360 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006361 Types.push_back(DefaultFlags |
6362 getMapTypeBits(
6363 /*MapType*/ OMPC_MAP_alloc,
6364 /*MapTypeModifier=*/OMPC_MAP_unknown,
6365 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006366 IsExpressionFirstInfo = false;
6367 IsCaptureFirstInfo = false;
6368 // The reference will be the next base address.
6369 BP = RefAddr;
6370 }
6371
6372 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006373 Pointers.push_back(LB);
6374 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006375
Samuel Antao6782e942016-05-26 16:48:10 +00006376 // We need to add a pointer flag for each map that comes from the
6377 // same expression except for the first one. We also need to signal
6378 // this map is the first one that relates with the current capture
6379 // (there is a set of entries for each capture).
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006380 Types.push_back(DefaultFlags | getMapTypeBits(MapType, MapTypeModifier,
6381 !IsExpressionFirstInfo,
6382 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006383
6384 // If we have a final array section, we are done with this expression.
6385 if (IsFinalArraySection)
6386 break;
6387
6388 // The pointer becomes the base for the next element.
6389 if (Next != CE)
6390 BP = LB;
6391
6392 IsExpressionFirstInfo = false;
6393 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006394 }
6395 }
6396 }
6397
Samuel Antaod486f842016-05-26 16:53:38 +00006398 /// \brief Return the adjusted map modifiers if the declaration a capture
6399 /// refers to appears in a first-private clause. This is expected to be used
6400 /// only with directives that start with 'target'.
6401 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6402 unsigned CurrentModifiers) {
6403 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6404
6405 // A first private variable captured by reference will use only the
6406 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6407 // declaration is known as first-private in this handler.
6408 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6409 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
6410 MappableExprsHandler::OMP_MAP_TO;
6411
6412 // We didn't modify anything.
6413 return CurrentModifiers;
6414 }
6415
Samuel Antao86ace552016-04-27 22:40:57 +00006416public:
6417 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006418 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006419 // Extract firstprivate clause information.
6420 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6421 for (const auto *D : C->varlists())
6422 FirstPrivateDecls.insert(
6423 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006424 // Extract device pointer clause information.
6425 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6426 for (auto L : C->component_lists())
6427 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006428 }
Samuel Antao86ace552016-04-27 22:40:57 +00006429
6430 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006431 /// types for the extracted mappable expressions. Also, for each item that
6432 /// relates with a device pointer, a pair of the relevant declaration and
6433 /// index where it occurs is appended to the device pointers info array.
6434 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006435 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6436 MapFlagsArrayTy &Types) const {
6437 BasePointers.clear();
6438 Pointers.clear();
6439 Sizes.clear();
6440 Types.clear();
6441
6442 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006443 /// Kind that defines how a device pointer has to be returned.
6444 enum ReturnPointerKind {
6445 // Don't have to return any pointer.
6446 RPK_None,
6447 // Pointer is the base of the declaration.
6448 RPK_Base,
6449 // Pointer is a member of the base declaration - 'this'
6450 RPK_Member,
6451 // Pointer is a reference and a member of the base declaration - 'this'
6452 RPK_MemberReference,
6453 };
Samuel Antao86ace552016-04-27 22:40:57 +00006454 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006455 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6456 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6457 ReturnPointerKind ReturnDevicePointer = RPK_None;
6458 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006459
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006460 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006461 MapInfo(
6462 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6463 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006464 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006465 : Components(Components), MapType(MapType),
6466 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006467 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006468 };
6469
6470 // We have to process the component lists that relate with the same
6471 // declaration in a single chunk so that we can generate the map flags
6472 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006473 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006474
6475 // Helper function to fill the information map for the different supported
6476 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006477 auto &&InfoGen = [&Info](
6478 const ValueDecl *D,
6479 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6480 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006481 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006482 const ValueDecl *VD =
6483 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006484 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6485 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006486 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006487
Paul Robinson78fb1322016-08-01 22:12:46 +00006488 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006489 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006490 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006491 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006492 MapInfo::RPK_None, C->isImplicit());
6493 }
Paul Robinson15c84002016-07-29 20:46:16 +00006494 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006495 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006496 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006497 MapInfo::RPK_None, C->isImplicit());
6498 }
Paul Robinson15c84002016-07-29 20:46:16 +00006499 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006500 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006501 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006502 MapInfo::RPK_None, C->isImplicit());
6503 }
Samuel Antao86ace552016-04-27 22:40:57 +00006504
Samuel Antaocc10b852016-07-28 14:23:26 +00006505 // Look at the use_device_ptr clause information and mark the existing map
6506 // entries as such. If there is no map information for an entry in the
6507 // use_device_ptr list, we create one with map type 'alloc' and zero size
6508 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006509 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006510 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006511 for (auto L : C->component_lists()) {
6512 assert(!L.second.empty() && "Not expecting empty list of components!");
6513 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6514 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6515 auto *IE = L.second.back().getAssociatedExpression();
6516 // If the first component is a member expression, we have to look into
6517 // 'this', which maps to null in the map of map information. Otherwise
6518 // look directly for the information.
6519 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6520
6521 // We potentially have map information for this declaration already.
6522 // Look for the first set of components that refer to it.
6523 if (It != Info.end()) {
6524 auto CI = std::find_if(
6525 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6526 return MI.Components.back().getAssociatedDeclaration() == VD;
6527 });
6528 // If we found a map entry, signal that the pointer has to be returned
6529 // and move on to the next declaration.
6530 if (CI != It->second.end()) {
6531 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6532 ? (VD->getType()->isReferenceType()
6533 ? MapInfo::RPK_MemberReference
6534 : MapInfo::RPK_Member)
6535 : MapInfo::RPK_Base;
6536 continue;
6537 }
6538 }
6539
6540 // We didn't find any match in our map information - generate a zero
6541 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006542 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006543 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006544 this->CGF
6545 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006546 .getScalarVal();
6547 BasePointers.push_back({Ptr, VD});
6548 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006549 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00006550 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6551 }
6552
Samuel Antao86ace552016-04-27 22:40:57 +00006553 for (auto &M : Info) {
6554 // We need to know when we generate information for the first component
6555 // associated with a capture, because the mapping flags depend on it.
6556 bool IsFirstComponentList = true;
6557 for (MapInfo &L : M.second) {
6558 assert(!L.Components.empty() &&
6559 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006560
6561 // Remember the current base pointer index.
6562 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006563 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006564 this->generateInfoForComponentList(
6565 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
6566 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006567
6568 // If this entry relates with a device pointer, set the relevant
6569 // declaration and add the 'return pointer' flag.
6570 if (IsFirstComponentList &&
6571 L.ReturnDevicePointer != MapInfo::RPK_None) {
6572 // If the pointer is not the base of the map, we need to skip the
6573 // base. If it is a reference in a member field, we also need to skip
6574 // the map of the reference.
6575 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6576 ++CurrentBasePointersIdx;
6577 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6578 ++CurrentBasePointersIdx;
6579 }
6580 assert(BasePointers.size() > CurrentBasePointersIdx &&
6581 "Unexpected number of mapped base pointers.");
6582
6583 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6584 assert(RelevantVD &&
6585 "No relevant declaration related with device pointer??");
6586
6587 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6588 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6589 }
Samuel Antao86ace552016-04-27 22:40:57 +00006590 IsFirstComponentList = false;
6591 }
6592 }
6593 }
6594
6595 /// \brief Generate the base pointers, section pointers, sizes and map types
6596 /// associated to a given capture.
6597 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006598 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006599 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006600 MapValuesArrayTy &Pointers,
6601 MapValuesArrayTy &Sizes,
6602 MapFlagsArrayTy &Types) const {
6603 assert(!Cap->capturesVariableArrayType() &&
6604 "Not expecting to generate map info for a variable array type!");
6605
6606 BasePointers.clear();
6607 Pointers.clear();
6608 Sizes.clear();
6609 Types.clear();
6610
Samuel Antao6890b092016-07-28 14:25:09 +00006611 // We need to know when we generating information for the first component
6612 // associated with a capture, because the mapping flags depend on it.
6613 bool IsFirstComponentList = true;
6614
Samuel Antao86ace552016-04-27 22:40:57 +00006615 const ValueDecl *VD =
6616 Cap->capturesThis()
6617 ? nullptr
6618 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6619
Samuel Antao6890b092016-07-28 14:25:09 +00006620 // If this declaration appears in a is_device_ptr clause we just have to
6621 // pass the pointer by value. If it is a reference to a declaration, we just
6622 // pass its value, otherwise, if it is a member expression, we need to map
6623 // 'to' the field.
6624 if (!VD) {
6625 auto It = DevPointersMap.find(VD);
6626 if (It != DevPointersMap.end()) {
6627 for (auto L : It->second) {
6628 generateInfoForComponentList(
6629 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006630 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
6631 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00006632 IsFirstComponentList = false;
6633 }
6634 return;
6635 }
6636 } else if (DevPointersMap.count(VD)) {
6637 BasePointers.push_back({Arg, VD});
6638 Pointers.push_back(Arg);
6639 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6640 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6641 return;
6642 }
6643
Paul Robinson78fb1322016-08-01 22:12:46 +00006644 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006645 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006646 for (auto L : C->decl_component_lists(VD)) {
6647 assert(L.first == VD &&
6648 "We got information for the wrong declaration??");
6649 assert(!L.second.empty() &&
6650 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006651 generateInfoForComponentList(
6652 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
6653 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00006654 IsFirstComponentList = false;
6655 }
6656
6657 return;
6658 }
Samuel Antaod486f842016-05-26 16:53:38 +00006659
6660 /// \brief Generate the default map information for a given capture \a CI,
6661 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006662 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6663 const FieldDecl &RI, llvm::Value *CV,
6664 MapBaseValuesArrayTy &CurBasePointers,
6665 MapValuesArrayTy &CurPointers,
6666 MapValuesArrayTy &CurSizes,
6667 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006668
6669 // Do the default mapping.
6670 if (CI.capturesThis()) {
6671 CurBasePointers.push_back(CV);
6672 CurPointers.push_back(CV);
6673 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6674 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6675 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006676 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006677 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006678 CurBasePointers.push_back(CV);
6679 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006680 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006681 // We have to signal to the runtime captures passed by value that are
6682 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00006683 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006684 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6685 } else {
6686 // Pointers are implicitly mapped with a zero size and no flags
6687 // (other than first map that is added for all implicit maps).
6688 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006689 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6690 }
6691 } else {
6692 assert(CI.capturesVariable() && "Expected captured reference.");
6693 CurBasePointers.push_back(CV);
6694 CurPointers.push_back(CV);
6695
6696 const ReferenceType *PtrTy =
6697 cast<ReferenceType>(RI.getType().getTypePtr());
6698 QualType ElementType = PtrTy->getPointeeType();
6699 CurSizes.push_back(CGF.getTypeSize(ElementType));
6700 // The default map type for a scalar/complex type is 'to' because by
6701 // default the value doesn't have to be retrieved. For an aggregate
6702 // type, the default is 'tofrom'.
6703 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006704 ? (OMP_MAP_TO | OMP_MAP_FROM)
6705 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006706
6707 // If we have a capture by reference we may need to add the private
6708 // pointer flag if the base declaration shows in some first-private
6709 // clause.
6710 CurMapTypes.back() =
6711 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6712 }
6713 // Every default map produces a single argument, so, it is always the
6714 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00006715 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00006716 }
Samuel Antao86ace552016-04-27 22:40:57 +00006717};
Samuel Antaodf158d52016-04-27 22:58:19 +00006718
6719enum OpenMPOffloadingReservedDeviceIDs {
6720 /// \brief Device ID if the device was not defined, runtime should get it
6721 /// from environment variables in the spec.
6722 OMP_DEVICEID_UNDEF = -1,
6723};
6724} // anonymous namespace
6725
6726/// \brief Emit the arrays used to pass the captures and map information to the
6727/// offloading runtime library. If there is no map or capture information,
6728/// return nullptr by reference.
6729static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006730emitOffloadingArrays(CodeGenFunction &CGF,
6731 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006732 MappableExprsHandler::MapValuesArrayTy &Pointers,
6733 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006734 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6735 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006736 auto &CGM = CGF.CGM;
6737 auto &Ctx = CGF.getContext();
6738
Samuel Antaocc10b852016-07-28 14:23:26 +00006739 // Reset the array information.
6740 Info.clearArrayInfo();
6741 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006742
Samuel Antaocc10b852016-07-28 14:23:26 +00006743 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006744 // Detect if we have any capture size requiring runtime evaluation of the
6745 // size so that a constant array could be eventually used.
6746 bool hasRuntimeEvaluationCaptureSize = false;
6747 for (auto *S : Sizes)
6748 if (!isa<llvm::Constant>(S)) {
6749 hasRuntimeEvaluationCaptureSize = true;
6750 break;
6751 }
6752
Samuel Antaocc10b852016-07-28 14:23:26 +00006753 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006754 QualType PointerArrayType =
6755 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6756 /*IndexTypeQuals=*/0);
6757
Samuel Antaocc10b852016-07-28 14:23:26 +00006758 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006759 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006760 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006761 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6762
6763 // If we don't have any VLA types or other types that require runtime
6764 // evaluation, we can use a constant array for the map sizes, otherwise we
6765 // need to fill up the arrays as we do for the pointers.
6766 if (hasRuntimeEvaluationCaptureSize) {
6767 QualType SizeArrayType = Ctx.getConstantArrayType(
6768 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6769 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006770 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006771 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6772 } else {
6773 // We expect all the sizes to be constant, so we collect them to create
6774 // a constant array.
6775 SmallVector<llvm::Constant *, 16> ConstSizes;
6776 for (auto S : Sizes)
6777 ConstSizes.push_back(cast<llvm::Constant>(S));
6778
6779 auto *SizesArrayInit = llvm::ConstantArray::get(
6780 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6781 auto *SizesArrayGbl = new llvm::GlobalVariable(
6782 CGM.getModule(), SizesArrayInit->getType(),
6783 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6784 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006785 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006786 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006787 }
6788
6789 // The map types are always constant so we don't need to generate code to
6790 // fill arrays. Instead, we create an array constant.
6791 llvm::Constant *MapTypesArrayInit =
6792 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6793 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6794 CGM.getModule(), MapTypesArrayInit->getType(),
6795 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6796 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006797 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006798 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006799
Samuel Antaocc10b852016-07-28 14:23:26 +00006800 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6801 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006802 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006803 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6804 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006805 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6806 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006807 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6808 CGF.Builder.CreateStore(BPVal, BPAddr);
6809
Samuel Antaocc10b852016-07-28 14:23:26 +00006810 if (Info.requiresDevicePointerInfo())
6811 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6812 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6813
Samuel Antaodf158d52016-04-27 22:58:19 +00006814 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006815 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006816 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6817 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006818 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6819 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006820 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6821 CGF.Builder.CreateStore(PVal, PAddr);
6822
6823 if (hasRuntimeEvaluationCaptureSize) {
6824 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006825 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6826 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006827 /*Idx0=*/0,
6828 /*Idx1=*/i);
6829 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6830 CGF.Builder.CreateStore(
6831 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6832 SAddr);
6833 }
6834 }
6835 }
6836}
6837/// \brief Emit the arguments to be passed to the runtime library based on the
6838/// arrays of pointers, sizes and map types.
6839static void emitOffloadingArraysArgument(
6840 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6841 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006842 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006843 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006844 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006845 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006846 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6847 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006848 /*Idx0=*/0, /*Idx1=*/0);
6849 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006850 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6851 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006852 /*Idx0=*/0,
6853 /*Idx1=*/0);
6854 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006855 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006856 /*Idx0=*/0, /*Idx1=*/0);
6857 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006858 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6859 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006860 /*Idx0=*/0,
6861 /*Idx1=*/0);
6862 } else {
6863 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6864 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6865 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6866 MapTypesArrayArg =
6867 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6868 }
Samuel Antao86ace552016-04-27 22:40:57 +00006869}
6870
Samuel Antaobed3c462015-10-02 16:14:20 +00006871void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6872 const OMPExecutableDirective &D,
6873 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006874 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006875 const Expr *IfCond, const Expr *Device,
6876 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006877 if (!CGF.HaveInsertPoint())
6878 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006879
Samuel Antaoee8fb302016-01-06 13:42:12 +00006880 assert(OutlinedFn && "Invalid outlined function!");
6881
Samuel Antao86ace552016-04-27 22:40:57 +00006882 // Fill up the arrays with all the captured variables.
6883 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006884 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006885 MappableExprsHandler::MapValuesArrayTy Pointers;
6886 MappableExprsHandler::MapValuesArrayTy Sizes;
6887 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006888
Samuel Antaocc10b852016-07-28 14:23:26 +00006889 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006890 MappableExprsHandler::MapValuesArrayTy CurPointers;
6891 MappableExprsHandler::MapValuesArrayTy CurSizes;
6892 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6893
Samuel Antaod486f842016-05-26 16:53:38 +00006894 // Get mappable expression information.
6895 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006896
6897 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6898 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006899 auto CV = CapturedVars.begin();
6900 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6901 CE = CS.capture_end();
6902 CI != CE; ++CI, ++RI, ++CV) {
Samuel Antao86ace552016-04-27 22:40:57 +00006903 CurBasePointers.clear();
6904 CurPointers.clear();
6905 CurSizes.clear();
6906 CurMapTypes.clear();
6907
6908 // VLA sizes are passed to the outlined region by copy and do not have map
6909 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006910 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006911 CurBasePointers.push_back(*CV);
6912 CurPointers.push_back(*CV);
6913 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006914 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006915 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6916 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006917 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006918 // If we have any information in the map clause, we use it, otherwise we
6919 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006920 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006921 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006922 if (CurBasePointers.empty())
6923 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6924 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006925 }
Samuel Antao86ace552016-04-27 22:40:57 +00006926 // We expect to have at least an element of information for this capture.
6927 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6928 assert(CurBasePointers.size() == CurPointers.size() &&
6929 CurBasePointers.size() == CurSizes.size() &&
6930 CurBasePointers.size() == CurMapTypes.size() &&
6931 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006932
Samuel Antao86ace552016-04-27 22:40:57 +00006933 // The kernel args are always the first elements of the base pointers
6934 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006935 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006936 // We need to append the results of this capture to what we already have.
6937 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6938 Pointers.append(CurPointers.begin(), CurPointers.end());
6939 Sizes.append(CurSizes.begin(), CurSizes.end());
6940 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006941 }
6942
Samuel Antaobed3c462015-10-02 16:14:20 +00006943 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev2a007e02017-10-02 14:20:58 +00006944 auto &&ThenGen = [this, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6945 OutlinedFn, OutlinedFnID, &D,
6946 &KernelArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006947 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006948 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006949 TargetDataInfo Info;
6950 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6951 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6952 Info.PointersArray, Info.SizesArray,
6953 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006954
6955 // On top of the arrays that were filled up, the target offloading call
6956 // takes as arguments the device id as well as the host pointer. The host
6957 // pointer is used by the runtime library to identify the current target
6958 // region, so it only has to be unique and not necessarily point to
6959 // anything. It could be the pointer to the outlined function that
6960 // implements the target region, but we aren't using that so that the
6961 // compiler doesn't need to keep that, and could therefore inline the host
6962 // function if proven worthwhile during optimization.
6963
Samuel Antaoee8fb302016-01-06 13:42:12 +00006964 // From this point on, we need to have an ID of the target region defined.
6965 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006966
6967 // Emit device ID if any.
6968 llvm::Value *DeviceID;
6969 if (Device)
6970 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006971 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006972 else
6973 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6974
Samuel Antaodf158d52016-04-27 22:58:19 +00006975 // Emit the number of elements in the offloading arrays.
6976 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6977
Samuel Antaob68e2db2016-03-03 16:20:23 +00006978 // Return value of the runtime offloading call.
6979 llvm::Value *Return;
6980
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006981 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6982 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006983
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006984 // The target region is an outlined function launched by the runtime
6985 // via calls __tgt_target() or __tgt_target_teams().
6986 //
6987 // __tgt_target() launches a target region with one team and one thread,
6988 // executing a serial region. This master thread may in turn launch
6989 // more threads within its team upon encountering a parallel region,
6990 // however, no additional teams can be launched on the device.
6991 //
6992 // __tgt_target_teams() launches a target region with one or more teams,
6993 // each with one or more threads. This call is required for target
6994 // constructs such as:
6995 // 'target teams'
6996 // 'target' / 'teams'
6997 // 'target teams distribute parallel for'
6998 // 'target parallel'
6999 // and so on.
7000 //
7001 // Note that on the host and CPU targets, the runtime implementation of
7002 // these calls simply call the outlined function without forking threads.
7003 // The outlined functions themselves have runtime calls to
7004 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7005 // the compiler in emitTeamsCall() and emitParallelCall().
7006 //
7007 // In contrast, on the NVPTX target, the implementation of
7008 // __tgt_target_teams() launches a GPU kernel with the requested number
7009 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007010 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007011 // If we have NumTeams defined this means that we have an enclosed teams
7012 // region. Therefore we also expect to have NumThreads defined. These two
7013 // values should be defined in the presence of a teams directive,
7014 // regardless of having any clauses associated. If the user is using teams
7015 // but no clauses, these two values will be the default that should be
7016 // passed to the runtime library - a 32-bit integer with the value zero.
7017 assert(NumThreads && "Thread limit expression should be available along "
7018 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007019 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007020 DeviceID, OutlinedFnID,
7021 PointerNum, Info.BasePointersArray,
7022 Info.PointersArray, Info.SizesArray,
7023 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007024 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007025 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007026 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007027 } else {
7028 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007029 DeviceID, OutlinedFnID,
7030 PointerNum, Info.BasePointersArray,
7031 Info.PointersArray, Info.SizesArray,
7032 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007033 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007034 OffloadingArgs);
7035 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007036
Alexey Bataev2a007e02017-10-02 14:20:58 +00007037 // Check the error code and execute the host version if required.
7038 llvm::BasicBlock *OffloadFailedBlock =
7039 CGF.createBasicBlock("omp_offload.failed");
7040 llvm::BasicBlock *OffloadContBlock =
7041 CGF.createBasicBlock("omp_offload.cont");
7042 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7043 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7044
7045 CGF.EmitBlock(OffloadFailedBlock);
7046 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
7047 CGF.EmitBranch(OffloadContBlock);
7048
7049 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007050 };
7051
Samuel Antaoee8fb302016-01-06 13:42:12 +00007052 // Notify that the host version must be executed.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007053 auto &&ElseGen = [this, &D, OutlinedFn, &KernelArgs](CodeGenFunction &CGF,
7054 PrePostActionTy &) {
7055 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn,
7056 KernelArgs);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007057 };
7058
7059 // If we have a target function ID it means that we need to support
7060 // offloading, otherwise, just execute on the host. We need to execute on host
7061 // regardless of the conditional in the if clause if, e.g., the user do not
7062 // specify target triples.
7063 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007064 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007065 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007066 else {
7067 RegionCodeGenTy ThenRCG(ThenGen);
7068 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007069 }
7070 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007071 RegionCodeGenTy ElseRCG(ElseGen);
7072 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007073 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007074}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007075
7076void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7077 StringRef ParentName) {
7078 if (!S)
7079 return;
7080
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007081 // Codegen OMP target directives that offload compute to the device.
7082 bool requiresDeviceCodegen =
7083 isa<OMPExecutableDirective>(S) &&
7084 isOpenMPTargetExecutionDirective(
7085 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007086
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007087 if (requiresDeviceCodegen) {
7088 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007089 unsigned DeviceID;
7090 unsigned FileID;
7091 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007092 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007093 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007094
7095 // Is this a target region that should not be emitted as an entry point? If
7096 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007097 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7098 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007099 return;
7100
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007101 switch (S->getStmtClass()) {
7102 case Stmt::OMPTargetDirectiveClass:
7103 CodeGenFunction::EmitOMPTargetDeviceFunction(
7104 CGM, ParentName, cast<OMPTargetDirective>(*S));
7105 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007106 case Stmt::OMPTargetParallelDirectiveClass:
7107 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7108 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7109 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007110 case Stmt::OMPTargetTeamsDirectiveClass:
7111 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7112 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7113 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007114 default:
7115 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7116 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007117 return;
7118 }
7119
7120 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007121 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007122 return;
7123
7124 scanForTargetRegionsFunctions(
7125 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7126 ParentName);
7127 return;
7128 }
7129
7130 // If this is a lambda function, look into its body.
7131 if (auto *L = dyn_cast<LambdaExpr>(S))
7132 S = L->getBody();
7133
7134 // Keep looking for target regions recursively.
7135 for (auto *II : S->children())
7136 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007137}
7138
7139bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7140 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7141
7142 // If emitting code for the host, we do not process FD here. Instead we do
7143 // the normal code generation.
7144 if (!CGM.getLangOpts().OpenMPIsDevice)
7145 return false;
7146
7147 // Try to detect target regions in the function.
7148 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7149
Samuel Antao4b75b872016-12-12 19:26:31 +00007150 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007151 // scanning. Therefore, we signal that this function is completely dealt
7152 // with.
7153 return true;
7154}
7155
7156bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7157 if (!CGM.getLangOpts().OpenMPIsDevice)
7158 return false;
7159
7160 // Check if there are Ctors/Dtors in this declaration and look for target
7161 // regions in it. We use the complete variant to produce the kernel name
7162 // mangling.
7163 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7164 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7165 for (auto *Ctor : RD->ctors()) {
7166 StringRef ParentName =
7167 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7168 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7169 }
7170 auto *Dtor = RD->getDestructor();
7171 if (Dtor) {
7172 StringRef ParentName =
7173 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7174 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7175 }
7176 }
7177
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007178 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007179 // implemented yet). Therefore we signal that GD was processed in this case.
7180 return true;
7181}
7182
7183bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7184 auto *VD = GD.getDecl();
7185 if (isa<FunctionDecl>(VD))
7186 return emitTargetFunctions(GD);
7187
7188 return emitTargetGlobalVariable(GD);
7189}
7190
7191llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7192 // If we have offloading in the current module, we need to emit the entries
7193 // now and register the offloading descriptor.
7194 createOffloadEntriesAndInfoMetadata();
7195
7196 // Create and register the offloading binary descriptors. This is the main
7197 // entity that captures all the information about offloading in the current
7198 // compilation unit.
7199 return createOffloadingBinaryDescriptorRegistration();
7200}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007201
7202void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7203 const OMPExecutableDirective &D,
7204 SourceLocation Loc,
7205 llvm::Value *OutlinedFn,
7206 ArrayRef<llvm::Value *> CapturedVars) {
7207 if (!CGF.HaveInsertPoint())
7208 return;
7209
7210 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7211 CodeGenFunction::RunCleanupsScope Scope(CGF);
7212
7213 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7214 llvm::Value *Args[] = {
7215 RTLoc,
7216 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7217 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7218 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7219 RealArgs.append(std::begin(Args), std::end(Args));
7220 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7221
7222 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7223 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7224}
7225
7226void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007227 const Expr *NumTeams,
7228 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007229 SourceLocation Loc) {
7230 if (!CGF.HaveInsertPoint())
7231 return;
7232
7233 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7234
Carlo Bertollic6872252016-04-04 15:55:02 +00007235 llvm::Value *NumTeamsVal =
7236 (NumTeams)
7237 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7238 CGF.CGM.Int32Ty, /* isSigned = */ true)
7239 : CGF.Builder.getInt32(0);
7240
7241 llvm::Value *ThreadLimitVal =
7242 (ThreadLimit)
7243 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7244 CGF.CGM.Int32Ty, /* isSigned = */ true)
7245 : CGF.Builder.getInt32(0);
7246
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007247 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007248 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7249 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007250 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7251 PushNumTeamsArgs);
7252}
Samuel Antaodf158d52016-04-27 22:58:19 +00007253
Samuel Antaocc10b852016-07-28 14:23:26 +00007254void CGOpenMPRuntime::emitTargetDataCalls(
7255 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7256 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007257 if (!CGF.HaveInsertPoint())
7258 return;
7259
Samuel Antaocc10b852016-07-28 14:23:26 +00007260 // Action used to replace the default codegen action and turn privatization
7261 // off.
7262 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007263
7264 // Generate the code for the opening of the data environment. Capture all the
7265 // arguments of the runtime call by reference because they are used in the
7266 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007267 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7268 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007269 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007270 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007271 MappableExprsHandler::MapValuesArrayTy Pointers;
7272 MappableExprsHandler::MapValuesArrayTy Sizes;
7273 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7274
7275 // Get map clause information.
7276 MappableExprsHandler MCHandler(D, CGF);
7277 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007278
7279 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007280 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007281
7282 llvm::Value *BasePointersArrayArg = nullptr;
7283 llvm::Value *PointersArrayArg = nullptr;
7284 llvm::Value *SizesArrayArg = nullptr;
7285 llvm::Value *MapTypesArrayArg = nullptr;
7286 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007287 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007288
7289 // Emit device ID if any.
7290 llvm::Value *DeviceID = nullptr;
7291 if (Device)
7292 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7293 CGF.Int32Ty, /*isSigned=*/true);
7294 else
7295 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7296
7297 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007298 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007299
7300 llvm::Value *OffloadingArgs[] = {
7301 DeviceID, PointerNum, BasePointersArrayArg,
7302 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7303 auto &RT = CGF.CGM.getOpenMPRuntime();
7304 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7305 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007306
7307 // If device pointer privatization is required, emit the body of the region
7308 // here. It will have to be duplicated: with and without privatization.
7309 if (!Info.CaptureDeviceAddrMap.empty())
7310 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007311 };
7312
7313 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007314 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007315 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007316
7317 llvm::Value *BasePointersArrayArg = nullptr;
7318 llvm::Value *PointersArrayArg = nullptr;
7319 llvm::Value *SizesArrayArg = nullptr;
7320 llvm::Value *MapTypesArrayArg = nullptr;
7321 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007322 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007323
7324 // Emit device ID if any.
7325 llvm::Value *DeviceID = nullptr;
7326 if (Device)
7327 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7328 CGF.Int32Ty, /*isSigned=*/true);
7329 else
7330 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7331
7332 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007333 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007334
7335 llvm::Value *OffloadingArgs[] = {
7336 DeviceID, PointerNum, BasePointersArrayArg,
7337 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7338 auto &RT = CGF.CGM.getOpenMPRuntime();
7339 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7340 OffloadingArgs);
7341 };
7342
Samuel Antaocc10b852016-07-28 14:23:26 +00007343 // If we need device pointer privatization, we need to emit the body of the
7344 // region with no privatization in the 'else' branch of the conditional.
7345 // Otherwise, we don't have to do anything.
7346 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7347 PrePostActionTy &) {
7348 if (!Info.CaptureDeviceAddrMap.empty()) {
7349 CodeGen.setAction(NoPrivAction);
7350 CodeGen(CGF);
7351 }
7352 };
7353
7354 // We don't have to do anything to close the region if the if clause evaluates
7355 // to false.
7356 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007357
7358 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007359 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007360 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007361 RegionCodeGenTy RCG(BeginThenGen);
7362 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007363 }
7364
Samuel Antaocc10b852016-07-28 14:23:26 +00007365 // If we don't require privatization of device pointers, we emit the body in
7366 // between the runtime calls. This avoids duplicating the body code.
7367 if (Info.CaptureDeviceAddrMap.empty()) {
7368 CodeGen.setAction(NoPrivAction);
7369 CodeGen(CGF);
7370 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007371
7372 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007373 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007374 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007375 RegionCodeGenTy RCG(EndThenGen);
7376 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007377 }
7378}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007379
Samuel Antao8d2d7302016-05-26 18:30:22 +00007380void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007381 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7382 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007383 if (!CGF.HaveInsertPoint())
7384 return;
7385
Samuel Antao8dd66282016-04-27 23:14:30 +00007386 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007387 isa<OMPTargetExitDataDirective>(D) ||
7388 isa<OMPTargetUpdateDirective>(D)) &&
7389 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007390
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007391 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007392 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007393 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007394 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007395 MappableExprsHandler::MapValuesArrayTy Pointers;
7396 MappableExprsHandler::MapValuesArrayTy Sizes;
7397 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7398
7399 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007400 MappableExprsHandler MEHandler(D, CGF);
7401 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007402
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007403 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007404 TargetDataInfo Info;
7405 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7406 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7407 Info.PointersArray, Info.SizesArray,
7408 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007409
7410 // Emit device ID if any.
7411 llvm::Value *DeviceID = nullptr;
7412 if (Device)
7413 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7414 CGF.Int32Ty, /*isSigned=*/true);
7415 else
7416 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7417
7418 // Emit the number of elements in the offloading arrays.
7419 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7420
7421 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007422 DeviceID, PointerNum, Info.BasePointersArray,
7423 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007424
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007425 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007426 // Select the right runtime function call for each expected standalone
7427 // directive.
7428 OpenMPRTLFunction RTLFn;
7429 switch (D.getDirectiveKind()) {
7430 default:
7431 llvm_unreachable("Unexpected standalone target data directive.");
7432 break;
7433 case OMPD_target_enter_data:
7434 RTLFn = OMPRTL__tgt_target_data_begin;
7435 break;
7436 case OMPD_target_exit_data:
7437 RTLFn = OMPRTL__tgt_target_data_end;
7438 break;
7439 case OMPD_target_update:
7440 RTLFn = OMPRTL__tgt_target_data_update;
7441 break;
7442 }
7443 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007444 };
7445
7446 // In the event we get an if clause, we don't have to take any action on the
7447 // else side.
7448 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7449
7450 if (IfCond) {
7451 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7452 } else {
7453 RegionCodeGenTy ThenGenRCG(ThenGen);
7454 ThenGenRCG(CGF);
7455 }
7456}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007457
7458namespace {
7459 /// Kind of parameter in a function with 'declare simd' directive.
7460 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7461 /// Attribute set of the parameter.
7462 struct ParamAttrTy {
7463 ParamKindTy Kind = Vector;
7464 llvm::APSInt StrideOrArg;
7465 llvm::APSInt Alignment;
7466 };
7467} // namespace
7468
7469static unsigned evaluateCDTSize(const FunctionDecl *FD,
7470 ArrayRef<ParamAttrTy> ParamAttrs) {
7471 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7472 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7473 // of that clause. The VLEN value must be power of 2.
7474 // In other case the notion of the function`s "characteristic data type" (CDT)
7475 // is used to compute the vector length.
7476 // CDT is defined in the following order:
7477 // a) For non-void function, the CDT is the return type.
7478 // b) If the function has any non-uniform, non-linear parameters, then the
7479 // CDT is the type of the first such parameter.
7480 // c) If the CDT determined by a) or b) above is struct, union, or class
7481 // type which is pass-by-value (except for the type that maps to the
7482 // built-in complex data type), the characteristic data type is int.
7483 // d) If none of the above three cases is applicable, the CDT is int.
7484 // The VLEN is then determined based on the CDT and the size of vector
7485 // register of that ISA for which current vector version is generated. The
7486 // VLEN is computed using the formula below:
7487 // VLEN = sizeof(vector_register) / sizeof(CDT),
7488 // where vector register size specified in section 3.2.1 Registers and the
7489 // Stack Frame of original AMD64 ABI document.
7490 QualType RetType = FD->getReturnType();
7491 if (RetType.isNull())
7492 return 0;
7493 ASTContext &C = FD->getASTContext();
7494 QualType CDT;
7495 if (!RetType.isNull() && !RetType->isVoidType())
7496 CDT = RetType;
7497 else {
7498 unsigned Offset = 0;
7499 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7500 if (ParamAttrs[Offset].Kind == Vector)
7501 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7502 ++Offset;
7503 }
7504 if (CDT.isNull()) {
7505 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7506 if (ParamAttrs[I + Offset].Kind == Vector) {
7507 CDT = FD->getParamDecl(I)->getType();
7508 break;
7509 }
7510 }
7511 }
7512 }
7513 if (CDT.isNull())
7514 CDT = C.IntTy;
7515 CDT = CDT->getCanonicalTypeUnqualified();
7516 if (CDT->isRecordType() || CDT->isUnionType())
7517 CDT = C.IntTy;
7518 return C.getTypeSize(CDT);
7519}
7520
7521static void
7522emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007523 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007524 ArrayRef<ParamAttrTy> ParamAttrs,
7525 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7526 struct ISADataTy {
7527 char ISA;
7528 unsigned VecRegSize;
7529 };
7530 ISADataTy ISAData[] = {
7531 {
7532 'b', 128
7533 }, // SSE
7534 {
7535 'c', 256
7536 }, // AVX
7537 {
7538 'd', 256
7539 }, // AVX2
7540 {
7541 'e', 512
7542 }, // AVX512
7543 };
7544 llvm::SmallVector<char, 2> Masked;
7545 switch (State) {
7546 case OMPDeclareSimdDeclAttr::BS_Undefined:
7547 Masked.push_back('N');
7548 Masked.push_back('M');
7549 break;
7550 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7551 Masked.push_back('N');
7552 break;
7553 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7554 Masked.push_back('M');
7555 break;
7556 }
7557 for (auto Mask : Masked) {
7558 for (auto &Data : ISAData) {
7559 SmallString<256> Buffer;
7560 llvm::raw_svector_ostream Out(Buffer);
7561 Out << "_ZGV" << Data.ISA << Mask;
7562 if (!VLENVal) {
7563 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7564 evaluateCDTSize(FD, ParamAttrs));
7565 } else
7566 Out << VLENVal;
7567 for (auto &ParamAttr : ParamAttrs) {
7568 switch (ParamAttr.Kind){
7569 case LinearWithVarStride:
7570 Out << 's' << ParamAttr.StrideOrArg;
7571 break;
7572 case Linear:
7573 Out << 'l';
7574 if (!!ParamAttr.StrideOrArg)
7575 Out << ParamAttr.StrideOrArg;
7576 break;
7577 case Uniform:
7578 Out << 'u';
7579 break;
7580 case Vector:
7581 Out << 'v';
7582 break;
7583 }
7584 if (!!ParamAttr.Alignment)
7585 Out << 'a' << ParamAttr.Alignment;
7586 }
7587 Out << '_' << Fn->getName();
7588 Fn->addFnAttr(Out.str());
7589 }
7590 }
7591}
7592
7593void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7594 llvm::Function *Fn) {
7595 ASTContext &C = CGM.getContext();
7596 FD = FD->getCanonicalDecl();
7597 // Map params to their positions in function decl.
7598 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7599 if (isa<CXXMethodDecl>(FD))
7600 ParamPositions.insert({FD, 0});
7601 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007602 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007603 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7604 ++ParamPos;
7605 }
7606 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7607 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7608 // Mark uniform parameters.
7609 for (auto *E : Attr->uniforms()) {
7610 E = E->IgnoreParenImpCasts();
7611 unsigned Pos;
7612 if (isa<CXXThisExpr>(E))
7613 Pos = ParamPositions[FD];
7614 else {
7615 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7616 ->getCanonicalDecl();
7617 Pos = ParamPositions[PVD];
7618 }
7619 ParamAttrs[Pos].Kind = Uniform;
7620 }
7621 // Get alignment info.
7622 auto NI = Attr->alignments_begin();
7623 for (auto *E : Attr->aligneds()) {
7624 E = E->IgnoreParenImpCasts();
7625 unsigned Pos;
7626 QualType ParmTy;
7627 if (isa<CXXThisExpr>(E)) {
7628 Pos = ParamPositions[FD];
7629 ParmTy = E->getType();
7630 } else {
7631 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7632 ->getCanonicalDecl();
7633 Pos = ParamPositions[PVD];
7634 ParmTy = PVD->getType();
7635 }
7636 ParamAttrs[Pos].Alignment =
7637 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7638 : llvm::APSInt::getUnsigned(
7639 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7640 .getQuantity());
7641 ++NI;
7642 }
7643 // Mark linear parameters.
7644 auto SI = Attr->steps_begin();
7645 auto MI = Attr->modifiers_begin();
7646 for (auto *E : Attr->linears()) {
7647 E = E->IgnoreParenImpCasts();
7648 unsigned Pos;
7649 if (isa<CXXThisExpr>(E))
7650 Pos = ParamPositions[FD];
7651 else {
7652 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7653 ->getCanonicalDecl();
7654 Pos = ParamPositions[PVD];
7655 }
7656 auto &ParamAttr = ParamAttrs[Pos];
7657 ParamAttr.Kind = Linear;
7658 if (*SI) {
7659 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7660 Expr::SE_AllowSideEffects)) {
7661 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7662 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7663 ParamAttr.Kind = LinearWithVarStride;
7664 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7665 ParamPositions[StridePVD->getCanonicalDecl()]);
7666 }
7667 }
7668 }
7669 }
7670 ++SI;
7671 ++MI;
7672 }
7673 llvm::APSInt VLENVal;
7674 if (const Expr *VLEN = Attr->getSimdlen())
7675 VLENVal = VLEN->EvaluateKnownConstInt(C);
7676 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7677 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7678 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7679 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7680 }
7681}
Alexey Bataev8b427062016-05-25 12:36:08 +00007682
7683namespace {
7684/// Cleanup action for doacross support.
7685class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7686public:
7687 static const int DoacrossFinArgs = 2;
7688
7689private:
7690 llvm::Value *RTLFn;
7691 llvm::Value *Args[DoacrossFinArgs];
7692
7693public:
7694 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7695 : RTLFn(RTLFn) {
7696 assert(CallArgs.size() == DoacrossFinArgs);
7697 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7698 }
7699 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7700 if (!CGF.HaveInsertPoint())
7701 return;
7702 CGF.EmitRuntimeCall(RTLFn, Args);
7703 }
7704};
7705} // namespace
7706
7707void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7708 const OMPLoopDirective &D) {
7709 if (!CGF.HaveInsertPoint())
7710 return;
7711
7712 ASTContext &C = CGM.getContext();
7713 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7714 RecordDecl *RD;
7715 if (KmpDimTy.isNull()) {
7716 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7717 // kmp_int64 lo; // lower
7718 // kmp_int64 up; // upper
7719 // kmp_int64 st; // stride
7720 // };
7721 RD = C.buildImplicitRecord("kmp_dim");
7722 RD->startDefinition();
7723 addFieldToRecordDecl(C, RD, Int64Ty);
7724 addFieldToRecordDecl(C, RD, Int64Ty);
7725 addFieldToRecordDecl(C, RD, Int64Ty);
7726 RD->completeDefinition();
7727 KmpDimTy = C.getRecordType(RD);
7728 } else
7729 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7730
7731 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7732 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7733 enum { LowerFD = 0, UpperFD, StrideFD };
7734 // Fill dims with data.
7735 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7736 // dims.upper = num_iterations;
7737 LValue UpperLVal =
7738 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7739 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7740 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7741 Int64Ty, D.getNumIterations()->getExprLoc());
7742 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7743 // dims.stride = 1;
7744 LValue StrideLVal =
7745 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7746 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7747 StrideLVal);
7748
7749 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7750 // kmp_int32 num_dims, struct kmp_dim * dims);
7751 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7752 getThreadID(CGF, D.getLocStart()),
7753 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7754 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7755 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7756
7757 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7758 CGF.EmitRuntimeCall(RTLFn, Args);
7759 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7760 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7761 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7762 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7763 llvm::makeArrayRef(FiniArgs));
7764}
7765
7766void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7767 const OMPDependClause *C) {
7768 QualType Int64Ty =
7769 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7770 const Expr *CounterVal = C->getCounterValue();
7771 assert(CounterVal);
7772 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7773 CounterVal->getType(), Int64Ty,
7774 CounterVal->getExprLoc());
7775 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7776 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7777 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7778 getThreadID(CGF, C->getLocStart()),
7779 CntAddr.getPointer()};
7780 llvm::Value *RTLFn;
7781 if (C->getDependencyKind() == OMPC_DEPEND_source)
7782 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7783 else {
7784 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7785 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7786 }
7787 CGF.EmitRuntimeCall(RTLFn, Args);
7788}
7789
Alexey Bataev3c595a62017-08-14 15:01:03 +00007790void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7791 ArrayRef<llvm::Value *> Args,
7792 SourceLocation Loc) const {
7793 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7794
7795 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007796 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007797 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007798 return;
7799 }
7800 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007801 CGF.EmitRuntimeCall(Callee, Args);
7802}
7803
7804void CGOpenMPRuntime::emitOutlinedFunctionCall(
7805 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7806 ArrayRef<llvm::Value *> Args) const {
7807 assert(Loc.isValid() && "Outlined function call location must be valid.");
7808 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007809}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007810
7811Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7812 const VarDecl *NativeParam,
7813 const VarDecl *TargetParam) const {
7814 return CGF.GetAddrOfLocalVar(NativeParam);
7815}