blob: 42b7d16dfdb62566441ce271c92401aacdeadd85 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
17#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000022#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000024#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000028#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000029#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000030#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000031
32using namespace clang;
33using namespace CodeGen;
34
Benjamin Kramerc52193f2014-10-10 13:57:57 +000035namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000036/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000037class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000039 /// \brief Kinds of OpenMP regions used in codegen.
40 enum CGOpenMPRegionKind {
41 /// \brief Region with outlined function for standalone 'parallel'
42 /// directive.
43 ParallelOutlinedRegion,
44 /// \brief Region with outlined function for standalone 'task' directive.
45 TaskOutlinedRegion,
46 /// \brief Region for constructs that do not require function outlining,
47 /// like 'for', 'sections', 'atomic' etc. directives.
48 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000049 /// \brief Region with outlined function for standalone 'target' directive.
50 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 };
Alexey Bataev18095712014-10-10 12:19:54 +000052
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000053 CGOpenMPRegionInfo(const CapturedStmt &CS,
54 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000055 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000058 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000059
60 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000061 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000063 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000064 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000065
66 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000067 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000068 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000069
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000071 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000072
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000073 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000074 /// \return LValue for thread id variable. This LValue always has type int32*.
75 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000076
Alexey Bataev48591dd2016-04-20 04:01:36 +000077 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000079 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080
Alexey Bataev81c7ea02015-07-03 09:56:58 +000081 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82
Alexey Bataev25e5b442015-09-15 12:52:43 +000083 bool hasCancel() const { return HasCancel; }
84
Alexey Bataev18095712014-10-10 12:19:54 +000085 static bool classof(const CGCapturedStmtInfo *Info) {
86 return Info->getKind() == CR_OpenMP;
87 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000088
Alexey Bataev48591dd2016-04-20 04:01:36 +000089 ~CGOpenMPRegionInfo() override = default;
90
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000091protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000092 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000093 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000094 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000095 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096};
Alexey Bataev18095712014-10-10 12:19:54 +000097
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000098/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000099class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000100public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000101 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000102 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000103 OpenMPDirectiveKind Kind, bool HasCancel,
104 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000105 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000107 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000110
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000111 /// \brief Get a variable or parameter for storing global thread id
112 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000113 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114
Alexey Bataev18095712014-10-10 12:19:54 +0000115 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000116 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000117
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000118 static bool classof(const CGCapturedStmtInfo *Info) {
119 return CGOpenMPRegionInfo::classof(Info) &&
120 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121 ParallelOutlinedRegion;
122 }
123
Alexey Bataev18095712014-10-10 12:19:54 +0000124private:
125 /// \brief A variable or parameter storing global thread id for OpenMP
126 /// constructs.
127 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000128 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000129};
130
Alexey Bataev62b63b12015-03-10 07:28:44 +0000131/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000132class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000134 class UntiedTaskActionTy final : public PrePostActionTy {
135 bool Untied;
136 const VarDecl *PartIDVar;
137 const RegionCodeGenTy UntiedCodeGen;
138 llvm::SwitchInst *UntiedSwitch = nullptr;
139
140 public:
141 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142 const RegionCodeGenTy &UntiedCodeGen)
143 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144 void Enter(CodeGenFunction &CGF) override {
145 if (Untied) {
146 // Emit task switching point.
147 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
148 CGF.GetAddrOfLocalVar(PartIDVar),
149 PartIDVar->getType()->castAs<PointerType>());
150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
151 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153 CGF.EmitBlock(DoneBB);
154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157 CGF.Builder.GetInsertBlock());
158 emitUntiedSwitch(CGF);
159 }
160 }
161 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 if (Untied) {
163 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167 PartIdLVal);
168 UntiedCodeGen(CGF);
169 CodeGenFunction::JumpDest CurPoint =
170 CGF.getJumpDestInCurrentScope(".untied.next.");
171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174 CGF.Builder.GetInsertBlock());
175 CGF.EmitBranchThroughCleanup(CurPoint);
176 CGF.EmitBlock(CurPoint.getBlock());
177 }
178 }
179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000182 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000183 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 OpenMPDirectiveKind Kind, bool HasCancel,
185 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000187 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
189 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
Alexey Bataev62b63b12015-03-10 07:28:44 +0000191 /// \brief Get a variable or parameter for storing global thread id
192 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
195 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197
Alexey Bataev62b63b12015-03-10 07:28:44 +0000198 /// \brief Get the name of the capture helper.
199 StringRef getHelperName() const override { return ".omp_outlined."; }
200
Alexey Bataev48591dd2016-04-20 04:01:36 +0000201 void emitUntiedSwitch(CodeGenFunction &CGF) override {
202 Action.emitUntiedSwitch(CGF);
203 }
204
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000205 static bool classof(const CGCapturedStmtInfo *Info) {
206 return CGOpenMPRegionInfo::classof(Info) &&
207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208 TaskOutlinedRegion;
209 }
210
Alexey Bataev62b63b12015-03-10 07:28:44 +0000211private:
212 /// \brief A variable or parameter storing global thread id for OpenMP
213 /// constructs.
214 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000215 /// Action for emitting code for untied tasks.
216 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000217};
218
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000219/// \brief API for inlined captured statement code generation in OpenMP
220/// constructs.
221class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000224 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000225 OpenMPDirectiveKind Kind, bool HasCancel)
226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000229
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000231 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 if (OuterRegionInfo)
233 return OuterRegionInfo->getContextValue();
234 llvm_unreachable("No context value for inlined OpenMP region");
235 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000236
Hans Wennborg7eb54642015-09-10 17:07:54 +0000237 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238 if (OuterRegionInfo) {
239 OuterRegionInfo->setContextValue(V);
240 return;
241 }
242 llvm_unreachable("No context value for inlined OpenMP region");
243 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000244
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000245 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 if (OuterRegionInfo)
248 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000249 // If there is no outer outlined region,no need to lookup in a list of
250 // captured variables, we can use the original one.
251 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000253
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000254 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000255 if (OuterRegionInfo)
256 return OuterRegionInfo->getThisFieldDecl();
257 return nullptr;
258 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000259
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000260 /// \brief Get a variable or parameter for storing global thread id
261 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000262 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 if (OuterRegionInfo)
264 return OuterRegionInfo->getThreadIDVariable();
265 return nullptr;
266 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000268 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000269 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000270 if (auto *OuterRegionInfo = getOldCSI())
271 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000272 llvm_unreachable("No helper name for inlined OpenMP construct");
273 }
274
Alexey Bataev48591dd2016-04-20 04:01:36 +0000275 void emitUntiedSwitch(CodeGenFunction &CGF) override {
276 if (OuterRegionInfo)
277 OuterRegionInfo->emitUntiedSwitch(CGF);
278 }
279
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000280 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
281
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000282 static bool classof(const CGCapturedStmtInfo *Info) {
283 return CGOpenMPRegionInfo::classof(Info) &&
284 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
285 }
286
Alexey Bataev48591dd2016-04-20 04:01:36 +0000287 ~CGOpenMPInlinedRegionInfo() override = default;
288
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000289private:
290 /// \brief CodeGen info about outer OpenMP region.
291 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
292 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000293};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000294
Samuel Antaobed3c462015-10-02 16:14:20 +0000295/// \brief API for captured statement code generation in OpenMP target
296/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000297/// captured fields. The name of the target region has to be unique in a given
298/// application so it is provided by the client, because only the client has
299/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000300class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000301public:
302 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000303 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000304 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000305 /*HasCancel=*/false),
306 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000307
308 /// \brief This is unused for target regions because each starts executing
309 /// with a single thread.
310 const VarDecl *getThreadIDVariable() const override { return nullptr; }
311
312 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000313 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000314
315 static bool classof(const CGCapturedStmtInfo *Info) {
316 return CGOpenMPRegionInfo::classof(Info) &&
317 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
318 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000319
320private:
321 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000322};
323
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000324static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000325 llvm_unreachable("No codegen for expressions");
326}
327/// \brief API for generation of expressions captured in a innermost OpenMP
328/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000329class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000330public:
331 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
332 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
333 OMPD_unknown,
334 /*HasCancel=*/false),
335 PrivScope(CGF) {
336 // Make sure the globals captured in the provided statement are local by
337 // using the privatization logic. We assume the same variable is not
338 // captured more than once.
339 for (auto &C : CS.captures()) {
340 if (!C.capturesVariable() && !C.capturesVariableByCopy())
341 continue;
342
343 const VarDecl *VD = C.getCapturedVar();
344 if (VD->isLocalVarDeclOrParm())
345 continue;
346
347 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
348 /*RefersToEnclosingVariableOrCapture=*/false,
349 VD->getType().getNonReferenceType(), VK_LValue,
350 SourceLocation());
351 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
352 return CGF.EmitLValue(&DRE).getAddress();
353 });
354 }
355 (void)PrivScope.Privatize();
356 }
357
358 /// \brief Lookup the captured field decl for a variable.
359 const FieldDecl *lookup(const VarDecl *VD) const override {
360 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
361 return FD;
362 return nullptr;
363 }
364
365 /// \brief Emit the captured statement body.
366 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
367 llvm_unreachable("No body for expressions");
368 }
369
370 /// \brief Get a variable or parameter for storing global thread id
371 /// inside OpenMP construct.
372 const VarDecl *getThreadIDVariable() const override {
373 llvm_unreachable("No thread id for expressions");
374 }
375
376 /// \brief Get the name of the capture helper.
377 StringRef getHelperName() const override {
378 llvm_unreachable("No helper name for expressions");
379 }
380
381 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
382
383private:
384 /// Private scope to capture global variables.
385 CodeGenFunction::OMPPrivateScope PrivScope;
386};
387
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000388/// \brief RAII for emitting code of OpenMP constructs.
389class InlinedOpenMPRegionRAII {
390 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000391 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
392 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000393
394public:
395 /// \brief Constructs region for combined constructs.
396 /// \param CodeGen Code generation sequence for combined directives. Includes
397 /// a list of functions used for code generation of implicitly inlined
398 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000399 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000400 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000401 : CGF(CGF) {
402 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000403 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
404 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000405 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
406 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
407 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000408 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000409
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000410 ~InlinedOpenMPRegionRAII() {
411 // Restore original CapturedStmtInfo only if we're done with code emission.
412 auto *OldCSI =
413 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
414 delete CGF.CapturedStmtInfo;
415 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000416 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
417 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000418 }
419};
420
Alexey Bataev50b3c952016-02-19 10:38:26 +0000421/// \brief Values for bit flags used in the ident_t to describe the fields.
422/// All enumeric elements are named and described in accordance with the code
423/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000424enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000425 /// \brief Use trampoline for internal microtask.
426 OMP_IDENT_IMD = 0x01,
427 /// \brief Use c-style ident structure.
428 OMP_IDENT_KMPC = 0x02,
429 /// \brief Atomic reduction option for kmpc_reduce.
430 OMP_ATOMIC_REDUCE = 0x10,
431 /// \brief Explicit 'barrier' directive.
432 OMP_IDENT_BARRIER_EXPL = 0x20,
433 /// \brief Implicit barrier in code.
434 OMP_IDENT_BARRIER_IMPL = 0x40,
435 /// \brief Implicit barrier in 'for' directive.
436 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
437 /// \brief Implicit barrier in 'sections' directive.
438 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
439 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000440 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
441 /// Call of __kmp_for_static_init for static loop.
442 OMP_IDENT_WORK_LOOP = 0x200,
443 /// Call of __kmp_for_static_init for sections.
444 OMP_IDENT_WORK_SECTIONS = 0x400,
445 /// Call of __kmp_for_static_init for distribute.
446 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
447 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000448};
449
450/// \brief Describes ident structure that describes a source location.
451/// All descriptions are taken from
452/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
453/// Original structure:
454/// typedef struct ident {
455/// kmp_int32 reserved_1; /**< might be used in Fortran;
456/// see above */
457/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
458/// KMP_IDENT_KMPC identifies this union
459/// member */
460/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
461/// see above */
462///#if USE_ITT_BUILD
463/// /* but currently used for storing
464/// region-specific ITT */
465/// /* contextual information. */
466///#endif /* USE_ITT_BUILD */
467/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
468/// C++ */
469/// char const *psource; /**< String describing the source location.
470/// The string is composed of semi-colon separated
471// fields which describe the source file,
472/// the function and a pair of line numbers that
473/// delimit the construct.
474/// */
475/// } ident_t;
476enum IdentFieldIndex {
477 /// \brief might be used in Fortran
478 IdentField_Reserved_1,
479 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
480 IdentField_Flags,
481 /// \brief Not really used in Fortran any more
482 IdentField_Reserved_2,
483 /// \brief Source[4] in Fortran, do not use for C++
484 IdentField_Reserved_3,
485 /// \brief String describing the source location. The string is composed of
486 /// semi-colon separated fields which describe the source file, the function
487 /// and a pair of line numbers that delimit the construct.
488 IdentField_PSource
489};
490
491/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
492/// the enum sched_type in kmp.h).
493enum OpenMPSchedType {
494 /// \brief Lower bound for default (unordered) versions.
495 OMP_sch_lower = 32,
496 OMP_sch_static_chunked = 33,
497 OMP_sch_static = 34,
498 OMP_sch_dynamic_chunked = 35,
499 OMP_sch_guided_chunked = 36,
500 OMP_sch_runtime = 37,
501 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000502 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000503 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000504 /// \brief Lower bound for 'ordered' versions.
505 OMP_ord_lower = 64,
506 OMP_ord_static_chunked = 65,
507 OMP_ord_static = 66,
508 OMP_ord_dynamic_chunked = 67,
509 OMP_ord_guided_chunked = 68,
510 OMP_ord_runtime = 69,
511 OMP_ord_auto = 70,
512 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000513 /// \brief dist_schedule types
514 OMP_dist_sch_static_chunked = 91,
515 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000516 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
517 /// Set if the monotonic schedule modifier was present.
518 OMP_sch_modifier_monotonic = (1 << 29),
519 /// Set if the nonmonotonic schedule modifier was present.
520 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000521};
522
523enum OpenMPRTLFunction {
524 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
525 /// kmpc_micro microtask, ...);
526 OMPRTL__kmpc_fork_call,
527 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
528 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
529 OMPRTL__kmpc_threadprivate_cached,
530 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
531 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
532 OMPRTL__kmpc_threadprivate_register,
533 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
534 OMPRTL__kmpc_global_thread_num,
535 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
536 // kmp_critical_name *crit);
537 OMPRTL__kmpc_critical,
538 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
539 // global_tid, kmp_critical_name *crit, uintptr_t hint);
540 OMPRTL__kmpc_critical_with_hint,
541 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
542 // kmp_critical_name *crit);
543 OMPRTL__kmpc_end_critical,
544 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
545 // global_tid);
546 OMPRTL__kmpc_cancel_barrier,
547 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
548 OMPRTL__kmpc_barrier,
549 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
550 OMPRTL__kmpc_for_static_fini,
551 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
552 // global_tid);
553 OMPRTL__kmpc_serialized_parallel,
554 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
555 // global_tid);
556 OMPRTL__kmpc_end_serialized_parallel,
557 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
558 // kmp_int32 num_threads);
559 OMPRTL__kmpc_push_num_threads,
560 // Call to void __kmpc_flush(ident_t *loc);
561 OMPRTL__kmpc_flush,
562 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
563 OMPRTL__kmpc_master,
564 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
565 OMPRTL__kmpc_end_master,
566 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
567 // int end_part);
568 OMPRTL__kmpc_omp_taskyield,
569 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
570 OMPRTL__kmpc_single,
571 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
572 OMPRTL__kmpc_end_single,
573 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
574 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
575 // kmp_routine_entry_t *task_entry);
576 OMPRTL__kmpc_omp_task_alloc,
577 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
578 // new_task);
579 OMPRTL__kmpc_omp_task,
580 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
581 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
582 // kmp_int32 didit);
583 OMPRTL__kmpc_copyprivate,
584 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
585 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
586 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
587 OMPRTL__kmpc_reduce,
588 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
589 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
590 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
591 // *lck);
592 OMPRTL__kmpc_reduce_nowait,
593 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
594 // kmp_critical_name *lck);
595 OMPRTL__kmpc_end_reduce,
596 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
597 // kmp_critical_name *lck);
598 OMPRTL__kmpc_end_reduce_nowait,
599 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
600 // kmp_task_t * new_task);
601 OMPRTL__kmpc_omp_task_begin_if0,
602 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
603 // kmp_task_t * new_task);
604 OMPRTL__kmpc_omp_task_complete_if0,
605 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
606 OMPRTL__kmpc_ordered,
607 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
608 OMPRTL__kmpc_end_ordered,
609 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
610 // global_tid);
611 OMPRTL__kmpc_omp_taskwait,
612 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
613 OMPRTL__kmpc_taskgroup,
614 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
615 OMPRTL__kmpc_end_taskgroup,
616 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
617 // int proc_bind);
618 OMPRTL__kmpc_push_proc_bind,
619 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
620 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
621 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
622 OMPRTL__kmpc_omp_task_with_deps,
623 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
624 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
625 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
626 OMPRTL__kmpc_omp_wait_deps,
627 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
628 // global_tid, kmp_int32 cncl_kind);
629 OMPRTL__kmpc_cancellationpoint,
630 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
631 // kmp_int32 cncl_kind);
632 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000633 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
634 // kmp_int32 num_teams, kmp_int32 thread_limit);
635 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000636 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
637 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000638 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000639 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
640 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
641 // sched, kmp_uint64 grainsize, void *task_dup);
642 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000643 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
644 // num_dims, struct kmp_dim *dims);
645 OMPRTL__kmpc_doacross_init,
646 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
647 OMPRTL__kmpc_doacross_fini,
648 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
649 // *vec);
650 OMPRTL__kmpc_doacross_post,
651 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
652 // *vec);
653 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000654 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
655 // *data);
656 OMPRTL__kmpc_task_reduction_init,
657 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
658 // *d);
659 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000660
661 //
662 // Offloading related calls
663 //
664 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
665 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
666 // *arg_types);
667 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000668 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
669 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
670 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
671 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000672 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
673 OMPRTL__tgt_register_lib,
674 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
675 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000676 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
677 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
678 OMPRTL__tgt_target_data_begin,
679 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
680 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
681 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000682 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
683 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
684 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000685};
686
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000687/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
688/// region.
689class CleanupTy final : public EHScopeStack::Cleanup {
690 PrePostActionTy *Action;
691
692public:
693 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
694 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
695 if (!CGF.HaveInsertPoint())
696 return;
697 Action->Exit(CGF);
698 }
699};
700
Hans Wennborg7eb54642015-09-10 17:07:54 +0000701} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000702
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000703void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
704 CodeGenFunction::RunCleanupsScope Scope(CGF);
705 if (PrePostAction) {
706 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
707 Callback(CodeGen, CGF, *PrePostAction);
708 } else {
709 PrePostActionTy Action;
710 Callback(CodeGen, CGF, Action);
711 }
712}
713
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000714/// Check if the combiner is a call to UDR combiner and if it is so return the
715/// UDR decl used for reduction.
716static const OMPDeclareReductionDecl *
717getReductionInit(const Expr *ReductionOp) {
718 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
719 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
720 if (auto *DRE =
721 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
722 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
723 return DRD;
724 return nullptr;
725}
726
727static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
728 const OMPDeclareReductionDecl *DRD,
729 const Expr *InitOp,
730 Address Private, Address Original,
731 QualType Ty) {
732 if (DRD->getInitializer()) {
733 std::pair<llvm::Function *, llvm::Function *> Reduction =
734 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
735 auto *CE = cast<CallExpr>(InitOp);
736 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
737 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
738 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
739 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
740 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
741 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
742 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
743 [=]() -> Address { return Private; });
744 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
745 [=]() -> Address { return Original; });
746 (void)PrivateScope.Privatize();
747 RValue Func = RValue::get(Reduction.second);
748 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
749 CGF.EmitIgnoredExpr(InitOp);
750 } else {
751 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
752 auto *GV = new llvm::GlobalVariable(
753 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
754 llvm::GlobalValue::PrivateLinkage, Init, ".init");
755 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
756 RValue InitRVal;
757 switch (CGF.getEvaluationKind(Ty)) {
758 case TEK_Scalar:
759 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
760 break;
761 case TEK_Complex:
762 InitRVal =
763 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
764 break;
765 case TEK_Aggregate:
766 InitRVal = RValue::getAggregate(LV.getAddress());
767 break;
768 }
769 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
770 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
771 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
772 /*IsInitializer=*/false);
773 }
774}
775
776/// \brief Emit initialization of arrays of complex types.
777/// \param DestAddr Address of the array.
778/// \param Type Type of array.
779/// \param Init Initial expression of array.
780/// \param SrcAddr Address of the original array.
781static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
782 QualType Type, const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000783 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000784 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000785 // Perform element-by-element initialization.
786 QualType ElementTy;
787
788 // Drill down to the base element type on both arrays.
789 auto ArrayTy = Type->getAsArrayTypeUnsafe();
790 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
791 DestAddr =
792 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
793 if (DRD)
794 SrcAddr =
795 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
796
797 llvm::Value *SrcBegin = nullptr;
798 if (DRD)
799 SrcBegin = SrcAddr.getPointer();
800 auto DestBegin = DestAddr.getPointer();
801 // Cast from pointer to array type to pointer to single element.
802 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
803 // The basic structure here is a while-do loop.
804 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
805 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
806 auto IsEmpty =
807 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
808 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
809
810 // Enter the loop body, making that address the current address.
811 auto EntryBB = CGF.Builder.GetInsertBlock();
812 CGF.EmitBlock(BodyBB);
813
814 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
815
816 llvm::PHINode *SrcElementPHI = nullptr;
817 Address SrcElementCurrent = Address::invalid();
818 if (DRD) {
819 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
820 "omp.arraycpy.srcElementPast");
821 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
822 SrcElementCurrent =
823 Address(SrcElementPHI,
824 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
825 }
826 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
827 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
828 DestElementPHI->addIncoming(DestBegin, EntryBB);
829 Address DestElementCurrent =
830 Address(DestElementPHI,
831 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
832
833 // Emit copy.
834 {
835 CodeGenFunction::RunCleanupsScope InitScope(CGF);
836 if (DRD && (DRD->getInitializer() || !Init)) {
837 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
838 SrcElementCurrent, ElementTy);
839 } else
840 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
841 /*IsInitializer=*/false);
842 }
843
844 if (DRD) {
845 // Shift the address forward by one element.
846 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
847 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
848 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
849 }
850
851 // Shift the address forward by one element.
852 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
853 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
854 // Check whether we've reached the end.
855 auto Done =
856 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
857 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
858 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
859
860 // Done.
861 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
862}
863
864LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
865 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
866 return CGF.EmitOMPArraySectionExpr(OASE);
867 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
868 return CGF.EmitLValue(ASE);
869 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
870 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
871 CGF.CapturedStmtInfo &&
872 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
873 E->getType(), VK_LValue, E->getExprLoc());
874 // Store the address of the original variable associated with the LHS
875 // implicit variable.
876 return CGF.EmitLValue(&DRE);
877}
878
879LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
880 const Expr *E) {
881 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
882 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
883 return LValue();
884}
885
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000886void ReductionCodeGen::emitAggregateInitialization(
887 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
888 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000889 // Emit VarDecl with copy init for arrays.
890 // Get the address of the original variable captured in current
891 // captured region.
892 auto *PrivateVD =
893 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000894 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
895 DRD ? ClausesData[N].ReductionOp : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000896 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000897}
898
899ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
900 ArrayRef<const Expr *> Privates,
901 ArrayRef<const Expr *> ReductionOps) {
902 ClausesData.reserve(Shareds.size());
903 SharedAddresses.reserve(Shareds.size());
904 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000905 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000906 auto IPriv = Privates.begin();
907 auto IRed = ReductionOps.begin();
908 for (const auto *Ref : Shareds) {
909 ClausesData.emplace_back(Ref, *IPriv, *IRed);
910 std::advance(IPriv, 1);
911 std::advance(IRed, 1);
912 }
913}
914
915void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
916 assert(SharedAddresses.size() == N &&
917 "Number of generated lvalues must be exactly N.");
918 SharedAddresses.emplace_back(emitSharedLValue(CGF, ClausesData[N].Ref),
919 emitSharedLValueUB(CGF, ClausesData[N].Ref));
920}
921
922void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
923 auto *PrivateVD =
924 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
925 QualType PrivateType = PrivateVD->getType();
926 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
927 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000928 Sizes.emplace_back(
929 CGF.getTypeSize(
930 SharedAddresses[N].first.getType().getNonReferenceType()),
931 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000932 return;
933 }
934 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000935 llvm::Value *SizeInChars;
936 llvm::Type *ElemType =
937 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
938 ->getElementType();
939 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 if (AsArraySection) {
941 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
942 SharedAddresses[N].first.getPointer());
943 Size = CGF.Builder.CreateNUWAdd(
944 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000945 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000946 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000947 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000948 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000949 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000950 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000951 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000952 CodeGenFunction::OpaqueValueMapping OpaqueMap(
953 CGF,
954 cast<OpaqueValueExpr>(
955 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
956 RValue::get(Size));
957 CGF.EmitVariablyModifiedType(PrivateType);
958}
959
960void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
961 llvm::Value *Size) {
962 auto *PrivateVD =
963 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
964 QualType PrivateType = PrivateVD->getType();
965 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
966 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000967 assert(!Size && !Sizes[N].second &&
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000968 "Size should be nullptr for non-variably modified redution "
969 "items.");
970 return;
971 }
972 CodeGenFunction::OpaqueValueMapping OpaqueMap(
973 CGF,
974 cast<OpaqueValueExpr>(
975 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
976 RValue::get(Size));
977 CGF.EmitVariablyModifiedType(PrivateType);
978}
979
980void ReductionCodeGen::emitInitialization(
981 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
982 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
983 assert(SharedAddresses.size() > N && "No variable was generated");
984 auto *PrivateVD =
985 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
986 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
987 QualType PrivateType = PrivateVD->getType();
988 PrivateAddr = CGF.Builder.CreateElementBitCast(
989 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
990 QualType SharedType = SharedAddresses[N].first.getType();
991 SharedLVal = CGF.MakeAddrLValue(
992 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
993 CGF.ConvertTypeForMem(SharedType)),
994 SharedType, SharedAddresses[N].first.getBaseInfo());
995 if (isa<OMPArraySectionExpr>(ClausesData[N].Ref) ||
996 CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000997 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000998 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
999 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1000 PrivateAddr, SharedLVal.getAddress(),
1001 SharedLVal.getType());
1002 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1003 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1004 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1005 PrivateVD->getType().getQualifiers(),
1006 /*IsInitializer=*/false);
1007 }
1008}
1009
1010bool ReductionCodeGen::needCleanups(unsigned N) {
1011 auto *PrivateVD =
1012 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1013 QualType PrivateType = PrivateVD->getType();
1014 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1015 return DTorKind != QualType::DK_none;
1016}
1017
1018void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1019 Address PrivateAddr) {
1020 auto *PrivateVD =
1021 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1022 QualType PrivateType = PrivateVD->getType();
1023 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1024 if (needCleanups(N)) {
1025 PrivateAddr = CGF.Builder.CreateElementBitCast(
1026 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1027 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1028 }
1029}
1030
1031static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1032 LValue BaseLV) {
1033 BaseTy = BaseTy.getNonReferenceType();
1034 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1035 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1036 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1037 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1038 else {
1039 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
1040 BaseTy->castAs<ReferenceType>());
1041 }
1042 BaseTy = BaseTy->getPointeeType();
1043 }
1044 return CGF.MakeAddrLValue(
1045 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1046 CGF.ConvertTypeForMem(ElTy)),
1047 BaseLV.getType(), BaseLV.getBaseInfo());
1048}
1049
1050static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1051 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1052 llvm::Value *Addr) {
1053 Address Tmp = Address::invalid();
1054 Address TopTmp = Address::invalid();
1055 Address MostTopTmp = Address::invalid();
1056 BaseTy = BaseTy.getNonReferenceType();
1057 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1058 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1059 Tmp = CGF.CreateMemTemp(BaseTy);
1060 if (TopTmp.isValid())
1061 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1062 else
1063 MostTopTmp = Tmp;
1064 TopTmp = Tmp;
1065 BaseTy = BaseTy->getPointeeType();
1066 }
1067 llvm::Type *Ty = BaseLVType;
1068 if (Tmp.isValid())
1069 Ty = Tmp.getElementType();
1070 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1071 if (Tmp.isValid()) {
1072 CGF.Builder.CreateStore(Addr, Tmp);
1073 return MostTopTmp;
1074 }
1075 return Address(Addr, BaseLVAlignment);
1076}
1077
1078Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1079 Address PrivateAddr) {
1080 const DeclRefExpr *DE;
1081 const VarDecl *OrigVD = nullptr;
1082 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1083 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1084 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1085 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1086 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1087 Base = TempASE->getBase()->IgnoreParenImpCasts();
1088 DE = cast<DeclRefExpr>(Base);
1089 OrigVD = cast<VarDecl>(DE->getDecl());
1090 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1091 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1092 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1093 Base = TempASE->getBase()->IgnoreParenImpCasts();
1094 DE = cast<DeclRefExpr>(Base);
1095 OrigVD = cast<VarDecl>(DE->getDecl());
1096 }
1097 if (OrigVD) {
1098 BaseDecls.emplace_back(OrigVD);
1099 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1100 LValue BaseLValue =
1101 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1102 OriginalBaseLValue);
1103 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1104 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1105 llvm::Value *Ptr =
1106 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1107 return castToBase(CGF, OrigVD->getType(),
1108 SharedAddresses[N].first.getType(),
1109 OriginalBaseLValue.getPointer()->getType(),
1110 OriginalBaseLValue.getAlignment(), Ptr);
1111 }
1112 BaseDecls.emplace_back(
1113 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1114 return PrivateAddr;
1115}
1116
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001117bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1118 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1119 return DRD && DRD->getInitializer();
1120}
1121
Alexey Bataev18095712014-10-10 12:19:54 +00001122LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001123 return CGF.EmitLoadOfPointerLValue(
1124 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1125 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001126}
1127
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001128void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001129 if (!CGF.HaveInsertPoint())
1130 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001131 // 1.2.2 OpenMP Language Terminology
1132 // Structured block - An executable statement with a single entry at the
1133 // top and a single exit at the bottom.
1134 // The point of exit cannot be a branch out of the structured block.
1135 // longjmp() and throw() must not violate the entry/exit criteria.
1136 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001137 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001138 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001139}
1140
Alexey Bataev62b63b12015-03-10 07:28:44 +00001141LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1142 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001143 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1144 getThreadIDVariable()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001145 LValueBaseInfo(AlignmentSource::Decl, false));
Alexey Bataev62b63b12015-03-10 07:28:44 +00001146}
1147
Alexey Bataev9959db52014-05-06 10:08:46 +00001148CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001149 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001150 IdentTy = llvm::StructType::create(
1151 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1152 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001153 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001154 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001155
1156 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001157}
1158
Alexey Bataev91797552015-03-18 04:13:55 +00001159void CGOpenMPRuntime::clear() {
1160 InternalVars.clear();
1161}
1162
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001163static llvm::Function *
1164emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1165 const Expr *CombinerInitializer, const VarDecl *In,
1166 const VarDecl *Out, bool IsCombiner) {
1167 // void .omp_combiner.(Ty *in, Ty *out);
1168 auto &C = CGM.getContext();
1169 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1170 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001171 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001172 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001173 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001174 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001175 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001176 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001177 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001178 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001179 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1180 auto *Fn = llvm::Function::Create(
1181 FnTy, llvm::GlobalValue::InternalLinkage,
1182 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1183 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001184 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001185 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001186 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001187 CodeGenFunction CGF(CGM);
1188 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1189 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1190 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1191 CodeGenFunction::OMPPrivateScope Scope(CGF);
1192 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1193 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1194 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1195 .getAddress();
1196 });
1197 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1198 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1199 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1200 .getAddress();
1201 });
1202 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001203 if (!IsCombiner && Out->hasInit() &&
1204 !CGF.isTrivialInitializer(Out->getInit())) {
1205 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1206 Out->getType().getQualifiers(),
1207 /*IsInitializer=*/true);
1208 }
1209 if (CombinerInitializer)
1210 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001211 Scope.ForceCleanup();
1212 CGF.FinishFunction();
1213 return Fn;
1214}
1215
1216void CGOpenMPRuntime::emitUserDefinedReduction(
1217 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1218 if (UDRMap.count(D) > 0)
1219 return;
1220 auto &C = CGM.getContext();
1221 if (!In || !Out) {
1222 In = &C.Idents.get("omp_in");
1223 Out = &C.Idents.get("omp_out");
1224 }
1225 llvm::Function *Combiner = emitCombinerOrInitializer(
1226 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1227 cast<VarDecl>(D->lookup(Out).front()),
1228 /*IsCombiner=*/true);
1229 llvm::Function *Initializer = nullptr;
1230 if (auto *Init = D->getInitializer()) {
1231 if (!Priv || !Orig) {
1232 Priv = &C.Idents.get("omp_priv");
1233 Orig = &C.Idents.get("omp_orig");
1234 }
1235 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001236 CGM, D->getType(),
1237 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1238 : nullptr,
1239 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001240 cast<VarDecl>(D->lookup(Priv).front()),
1241 /*IsCombiner=*/false);
1242 }
1243 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1244 if (CGF) {
1245 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1246 Decls.second.push_back(D);
1247 }
1248}
1249
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001250std::pair<llvm::Function *, llvm::Function *>
1251CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1252 auto I = UDRMap.find(D);
1253 if (I != UDRMap.end())
1254 return I->second;
1255 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1256 return UDRMap.lookup(D);
1257}
1258
John McCall7f416cc2015-09-08 08:05:57 +00001259// Layout information for ident_t.
1260static CharUnits getIdentAlign(CodeGenModule &CGM) {
1261 return CGM.getPointerAlign();
1262}
1263static CharUnits getIdentSize(CodeGenModule &CGM) {
1264 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1265 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1266}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001267static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001268 // All the fields except the last are i32, so this works beautifully.
1269 return unsigned(Field) * CharUnits::fromQuantity(4);
1270}
1271static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001272 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001273 const llvm::Twine &Name = "") {
1274 auto Offset = getOffsetOfIdentField(Field);
1275 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1276}
1277
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001278static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1279 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1280 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1281 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001282 assert(ThreadIDVar->getType()->isPointerType() &&
1283 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001284 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001285 bool HasCancel = false;
1286 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1287 HasCancel = OPD->hasCancel();
1288 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1289 HasCancel = OPSD->hasCancel();
1290 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1291 HasCancel = OPFD->hasCancel();
1292 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001293 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001294 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001295 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001296}
1297
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001298llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1299 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1300 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1301 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1302 return emitParallelOrTeamsOutlinedFunction(
1303 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1304}
1305
1306llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1307 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1308 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1309 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1310 return emitParallelOrTeamsOutlinedFunction(
1311 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1312}
1313
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001314llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1315 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001316 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1317 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1318 bool Tied, unsigned &NumberOfParts) {
1319 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1320 PrePostActionTy &) {
1321 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1322 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1323 llvm::Value *TaskArgs[] = {
1324 UpLoc, ThreadID,
1325 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1326 TaskTVar->getType()->castAs<PointerType>())
1327 .getPointer()};
1328 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1329 };
1330 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1331 UntiedCodeGen);
1332 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001333 assert(!ThreadIDVar->getType()->isPointerType() &&
1334 "thread id variable must be of type kmp_int32 for tasks");
1335 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001336 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001337 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001338 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1339 InnermostKind,
1340 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001341 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001342 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1343 if (!Tied)
1344 NumberOfParts = Action.getNumberOfParts();
1345 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001346}
1347
Alexey Bataev50b3c952016-02-19 10:38:26 +00001348Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001349 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001350 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001351 if (!Entry) {
1352 if (!DefaultOpenMPPSource) {
1353 // Initialize default location for psource field of ident_t structure of
1354 // all ident_t objects. Format is ";file;function;line;column;;".
1355 // Taken from
1356 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1357 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001358 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001359 DefaultOpenMPPSource =
1360 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1361 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001362
John McCall23c9dc62016-11-28 22:18:27 +00001363 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001364 auto fields = builder.beginStruct(IdentTy);
1365 fields.addInt(CGM.Int32Ty, 0);
1366 fields.addInt(CGM.Int32Ty, Flags);
1367 fields.addInt(CGM.Int32Ty, 0);
1368 fields.addInt(CGM.Int32Ty, 0);
1369 fields.add(DefaultOpenMPPSource);
1370 auto DefaultOpenMPLocation =
1371 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1372 llvm::GlobalValue::PrivateLinkage);
1373 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1374
John McCall7f416cc2015-09-08 08:05:57 +00001375 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001376 }
John McCall7f416cc2015-09-08 08:05:57 +00001377 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001378}
1379
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001380llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1381 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001382 unsigned Flags) {
1383 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001384 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001385 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001386 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001387 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001388
1389 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1390
John McCall7f416cc2015-09-08 08:05:57 +00001391 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001392 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1393 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001394 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1395
Alexander Musmanc6388682014-12-15 07:07:06 +00001396 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1397 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001398 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001399 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001400 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1401 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001402 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001403 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001404 LocValue = AI;
1405
1406 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1407 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001408 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001409 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001410 }
1411
1412 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001413 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001414
Alexey Bataevf002aca2014-05-30 05:48:40 +00001415 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1416 if (OMPDebugLoc == nullptr) {
1417 SmallString<128> Buffer2;
1418 llvm::raw_svector_ostream OS2(Buffer2);
1419 // Build debug location
1420 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1421 OS2 << ";" << PLoc.getFilename() << ";";
1422 if (const FunctionDecl *FD =
1423 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1424 OS2 << FD->getQualifiedNameAsString();
1425 }
1426 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1427 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1428 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001429 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001430 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001431 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1432
John McCall7f416cc2015-09-08 08:05:57 +00001433 // Our callers always pass this to a runtime function, so for
1434 // convenience, go ahead and return a naked pointer.
1435 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001436}
1437
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001438llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1439 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001440 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1441
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001442 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001443 // Check whether we've already cached a load of the thread id in this
1444 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001445 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001446 if (I != OpenMPLocThreadIDMap.end()) {
1447 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001448 if (ThreadID != nullptr)
1449 return ThreadID;
1450 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001451 // If exceptions are enabled, do not use parameter to avoid possible crash.
1452 if (!CGF.getInvokeDest()) {
1453 if (auto *OMPRegionInfo =
1454 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1455 if (OMPRegionInfo->getThreadIDVariable()) {
1456 // Check if this an outlined function with thread id passed as argument.
1457 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1458 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1459 // If value loaded in entry block, cache it and use it everywhere in
1460 // function.
1461 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1462 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1463 Elem.second.ThreadID = ThreadID;
1464 }
1465 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001466 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001467 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001468 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001469
1470 // This is not an outlined function region - need to call __kmpc_int32
1471 // kmpc_global_thread_num(ident_t *loc).
1472 // Generate thread id value and cache this value for use across the
1473 // function.
1474 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1475 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1476 ThreadID =
1477 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1478 emitUpdateLocation(CGF, Loc));
1479 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1480 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001481 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001482}
1483
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001484void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001485 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001486 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1487 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001488 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1489 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1490 UDRMap.erase(D);
1491 }
1492 FunctionUDRMap.erase(CGF.CurFn);
1493 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001494}
1495
1496llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001497 if (!IdentTy) {
1498 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001499 return llvm::PointerType::getUnqual(IdentTy);
1500}
1501
1502llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001503 if (!Kmpc_MicroTy) {
1504 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1505 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1506 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1507 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1508 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001509 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1510}
1511
1512llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001513CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001514 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001515 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001516 case OMPRTL__kmpc_fork_call: {
1517 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1518 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001519 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1520 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001521 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001522 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001523 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1524 break;
1525 }
1526 case OMPRTL__kmpc_global_thread_num: {
1527 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001528 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001529 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001530 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001531 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1532 break;
1533 }
Alexey Bataev97720002014-11-11 04:05:39 +00001534 case OMPRTL__kmpc_threadprivate_cached: {
1535 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1536 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1537 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1538 CGM.VoidPtrTy, CGM.SizeTy,
1539 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1540 llvm::FunctionType *FnTy =
1541 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1542 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1543 break;
1544 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001545 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001546 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1547 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001548 llvm::Type *TypeParams[] = {
1549 getIdentTyPointerTy(), CGM.Int32Ty,
1550 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1551 llvm::FunctionType *FnTy =
1552 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1553 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1554 break;
1555 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001556 case OMPRTL__kmpc_critical_with_hint: {
1557 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1558 // kmp_critical_name *crit, uintptr_t hint);
1559 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1560 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1561 CGM.IntPtrTy};
1562 llvm::FunctionType *FnTy =
1563 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1564 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1565 break;
1566 }
Alexey Bataev97720002014-11-11 04:05:39 +00001567 case OMPRTL__kmpc_threadprivate_register: {
1568 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1569 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1570 // typedef void *(*kmpc_ctor)(void *);
1571 auto KmpcCtorTy =
1572 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1573 /*isVarArg*/ false)->getPointerTo();
1574 // typedef void *(*kmpc_cctor)(void *, void *);
1575 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1576 auto KmpcCopyCtorTy =
1577 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1578 /*isVarArg*/ false)->getPointerTo();
1579 // typedef void (*kmpc_dtor)(void *);
1580 auto KmpcDtorTy =
1581 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1582 ->getPointerTo();
1583 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1584 KmpcCopyCtorTy, KmpcDtorTy};
1585 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1586 /*isVarArg*/ false);
1587 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1588 break;
1589 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001590 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001591 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1592 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001593 llvm::Type *TypeParams[] = {
1594 getIdentTyPointerTy(), CGM.Int32Ty,
1595 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1596 llvm::FunctionType *FnTy =
1597 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1599 break;
1600 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001601 case OMPRTL__kmpc_cancel_barrier: {
1602 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1603 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001604 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1605 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001606 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1607 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001608 break;
1609 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001610 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001611 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001612 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1613 llvm::FunctionType *FnTy =
1614 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1615 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1616 break;
1617 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001618 case OMPRTL__kmpc_for_static_fini: {
1619 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1620 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1621 llvm::FunctionType *FnTy =
1622 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1623 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1624 break;
1625 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001626 case OMPRTL__kmpc_push_num_threads: {
1627 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1628 // kmp_int32 num_threads)
1629 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1630 CGM.Int32Ty};
1631 llvm::FunctionType *FnTy =
1632 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1633 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1634 break;
1635 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001636 case OMPRTL__kmpc_serialized_parallel: {
1637 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1638 // global_tid);
1639 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1640 llvm::FunctionType *FnTy =
1641 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1642 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1643 break;
1644 }
1645 case OMPRTL__kmpc_end_serialized_parallel: {
1646 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1647 // global_tid);
1648 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1649 llvm::FunctionType *FnTy =
1650 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1651 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1652 break;
1653 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001654 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001655 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001656 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1657 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001658 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001659 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1660 break;
1661 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001662 case OMPRTL__kmpc_master: {
1663 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1664 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1665 llvm::FunctionType *FnTy =
1666 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1667 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1668 break;
1669 }
1670 case OMPRTL__kmpc_end_master: {
1671 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1673 llvm::FunctionType *FnTy =
1674 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1675 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1676 break;
1677 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001678 case OMPRTL__kmpc_omp_taskyield: {
1679 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1680 // int end_part);
1681 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1682 llvm::FunctionType *FnTy =
1683 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1684 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1685 break;
1686 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001687 case OMPRTL__kmpc_single: {
1688 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1689 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1690 llvm::FunctionType *FnTy =
1691 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1692 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1693 break;
1694 }
1695 case OMPRTL__kmpc_end_single: {
1696 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1697 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1698 llvm::FunctionType *FnTy =
1699 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1700 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1701 break;
1702 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001703 case OMPRTL__kmpc_omp_task_alloc: {
1704 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1705 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1706 // kmp_routine_entry_t *task_entry);
1707 assert(KmpRoutineEntryPtrTy != nullptr &&
1708 "Type kmp_routine_entry_t must be created.");
1709 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1710 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1711 // Return void * and then cast to particular kmp_task_t type.
1712 llvm::FunctionType *FnTy =
1713 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1714 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1715 break;
1716 }
1717 case OMPRTL__kmpc_omp_task: {
1718 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1719 // *new_task);
1720 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1721 CGM.VoidPtrTy};
1722 llvm::FunctionType *FnTy =
1723 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1724 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1725 break;
1726 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001727 case OMPRTL__kmpc_copyprivate: {
1728 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001729 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001730 // kmp_int32 didit);
1731 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1732 auto *CpyFnTy =
1733 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001734 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001735 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1736 CGM.Int32Ty};
1737 llvm::FunctionType *FnTy =
1738 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1739 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1740 break;
1741 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001742 case OMPRTL__kmpc_reduce: {
1743 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1744 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1745 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1746 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1747 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1748 /*isVarArg=*/false);
1749 llvm::Type *TypeParams[] = {
1750 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1751 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1752 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1753 llvm::FunctionType *FnTy =
1754 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1755 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1756 break;
1757 }
1758 case OMPRTL__kmpc_reduce_nowait: {
1759 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1760 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1761 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1762 // *lck);
1763 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1764 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1765 /*isVarArg=*/false);
1766 llvm::Type *TypeParams[] = {
1767 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1768 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1769 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1770 llvm::FunctionType *FnTy =
1771 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1772 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1773 break;
1774 }
1775 case OMPRTL__kmpc_end_reduce: {
1776 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1777 // kmp_critical_name *lck);
1778 llvm::Type *TypeParams[] = {
1779 getIdentTyPointerTy(), CGM.Int32Ty,
1780 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1781 llvm::FunctionType *FnTy =
1782 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1783 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1784 break;
1785 }
1786 case OMPRTL__kmpc_end_reduce_nowait: {
1787 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1788 // kmp_critical_name *lck);
1789 llvm::Type *TypeParams[] = {
1790 getIdentTyPointerTy(), CGM.Int32Ty,
1791 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1792 llvm::FunctionType *FnTy =
1793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1794 RTLFn =
1795 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1796 break;
1797 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001798 case OMPRTL__kmpc_omp_task_begin_if0: {
1799 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1800 // *new_task);
1801 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1802 CGM.VoidPtrTy};
1803 llvm::FunctionType *FnTy =
1804 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1805 RTLFn =
1806 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1807 break;
1808 }
1809 case OMPRTL__kmpc_omp_task_complete_if0: {
1810 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1811 // *new_task);
1812 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1813 CGM.VoidPtrTy};
1814 llvm::FunctionType *FnTy =
1815 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1816 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1817 /*Name=*/"__kmpc_omp_task_complete_if0");
1818 break;
1819 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001820 case OMPRTL__kmpc_ordered: {
1821 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1822 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1823 llvm::FunctionType *FnTy =
1824 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1825 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1826 break;
1827 }
1828 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001829 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001830 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1831 llvm::FunctionType *FnTy =
1832 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1833 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1834 break;
1835 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001836 case OMPRTL__kmpc_omp_taskwait: {
1837 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1838 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1839 llvm::FunctionType *FnTy =
1840 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1841 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1842 break;
1843 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001844 case OMPRTL__kmpc_taskgroup: {
1845 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1846 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1847 llvm::FunctionType *FnTy =
1848 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1849 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1850 break;
1851 }
1852 case OMPRTL__kmpc_end_taskgroup: {
1853 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1854 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1855 llvm::FunctionType *FnTy =
1856 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1857 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1858 break;
1859 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001860 case OMPRTL__kmpc_push_proc_bind: {
1861 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1862 // int proc_bind)
1863 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1864 llvm::FunctionType *FnTy =
1865 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1866 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1867 break;
1868 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001869 case OMPRTL__kmpc_omp_task_with_deps: {
1870 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1871 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1872 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1873 llvm::Type *TypeParams[] = {
1874 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1875 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1876 llvm::FunctionType *FnTy =
1877 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1878 RTLFn =
1879 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1880 break;
1881 }
1882 case OMPRTL__kmpc_omp_wait_deps: {
1883 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1884 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1885 // kmp_depend_info_t *noalias_dep_list);
1886 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1887 CGM.Int32Ty, CGM.VoidPtrTy,
1888 CGM.Int32Ty, CGM.VoidPtrTy};
1889 llvm::FunctionType *FnTy =
1890 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1891 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1892 break;
1893 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001894 case OMPRTL__kmpc_cancellationpoint: {
1895 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1896 // global_tid, kmp_int32 cncl_kind)
1897 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1898 llvm::FunctionType *FnTy =
1899 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1900 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1901 break;
1902 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001903 case OMPRTL__kmpc_cancel: {
1904 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1905 // kmp_int32 cncl_kind)
1906 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1907 llvm::FunctionType *FnTy =
1908 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1909 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1910 break;
1911 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001912 case OMPRTL__kmpc_push_num_teams: {
1913 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1914 // kmp_int32 num_teams, kmp_int32 num_threads)
1915 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1916 CGM.Int32Ty};
1917 llvm::FunctionType *FnTy =
1918 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1919 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1920 break;
1921 }
1922 case OMPRTL__kmpc_fork_teams: {
1923 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1924 // microtask, ...);
1925 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1926 getKmpc_MicroPointerTy()};
1927 llvm::FunctionType *FnTy =
1928 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1929 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1930 break;
1931 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001932 case OMPRTL__kmpc_taskloop: {
1933 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1934 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1935 // sched, kmp_uint64 grainsize, void *task_dup);
1936 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1937 CGM.IntTy,
1938 CGM.VoidPtrTy,
1939 CGM.IntTy,
1940 CGM.Int64Ty->getPointerTo(),
1941 CGM.Int64Ty->getPointerTo(),
1942 CGM.Int64Ty,
1943 CGM.IntTy,
1944 CGM.IntTy,
1945 CGM.Int64Ty,
1946 CGM.VoidPtrTy};
1947 llvm::FunctionType *FnTy =
1948 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1949 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1950 break;
1951 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001952 case OMPRTL__kmpc_doacross_init: {
1953 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1954 // num_dims, struct kmp_dim *dims);
1955 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1956 CGM.Int32Ty,
1957 CGM.Int32Ty,
1958 CGM.VoidPtrTy};
1959 llvm::FunctionType *FnTy =
1960 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1961 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1962 break;
1963 }
1964 case OMPRTL__kmpc_doacross_fini: {
1965 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1966 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1967 llvm::FunctionType *FnTy =
1968 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1969 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1970 break;
1971 }
1972 case OMPRTL__kmpc_doacross_post: {
1973 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1974 // *vec);
1975 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1976 CGM.Int64Ty->getPointerTo()};
1977 llvm::FunctionType *FnTy =
1978 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1979 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1980 break;
1981 }
1982 case OMPRTL__kmpc_doacross_wait: {
1983 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1984 // *vec);
1985 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1986 CGM.Int64Ty->getPointerTo()};
1987 llvm::FunctionType *FnTy =
1988 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1989 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1990 break;
1991 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001992 case OMPRTL__kmpc_task_reduction_init: {
1993 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1994 // *data);
1995 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
1996 llvm::FunctionType *FnTy =
1997 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1998 RTLFn =
1999 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2000 break;
2001 }
2002 case OMPRTL__kmpc_task_reduction_get_th_data: {
2003 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2004 // *d);
2005 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2006 llvm::FunctionType *FnTy =
2007 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2008 RTLFn = CGM.CreateRuntimeFunction(
2009 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2010 break;
2011 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002012 case OMPRTL__tgt_target: {
2013 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
2014 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
2015 // *arg_types);
2016 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2017 CGM.VoidPtrTy,
2018 CGM.Int32Ty,
2019 CGM.VoidPtrPtrTy,
2020 CGM.VoidPtrPtrTy,
2021 CGM.SizeTy->getPointerTo(),
2022 CGM.Int32Ty->getPointerTo()};
2023 llvm::FunctionType *FnTy =
2024 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2025 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2026 break;
2027 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002028 case OMPRTL__tgt_target_teams: {
2029 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2030 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2031 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2032 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2033 CGM.VoidPtrTy,
2034 CGM.Int32Ty,
2035 CGM.VoidPtrPtrTy,
2036 CGM.VoidPtrPtrTy,
2037 CGM.SizeTy->getPointerTo(),
2038 CGM.Int32Ty->getPointerTo(),
2039 CGM.Int32Ty,
2040 CGM.Int32Ty};
2041 llvm::FunctionType *FnTy =
2042 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2043 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2044 break;
2045 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002046 case OMPRTL__tgt_register_lib: {
2047 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2048 QualType ParamTy =
2049 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2050 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2051 llvm::FunctionType *FnTy =
2052 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2053 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2054 break;
2055 }
2056 case OMPRTL__tgt_unregister_lib: {
2057 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2058 QualType ParamTy =
2059 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2060 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2061 llvm::FunctionType *FnTy =
2062 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2063 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2064 break;
2065 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002066 case OMPRTL__tgt_target_data_begin: {
2067 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2068 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2069 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2070 CGM.Int32Ty,
2071 CGM.VoidPtrPtrTy,
2072 CGM.VoidPtrPtrTy,
2073 CGM.SizeTy->getPointerTo(),
2074 CGM.Int32Ty->getPointerTo()};
2075 llvm::FunctionType *FnTy =
2076 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2077 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2078 break;
2079 }
2080 case OMPRTL__tgt_target_data_end: {
2081 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2082 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2083 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2084 CGM.Int32Ty,
2085 CGM.VoidPtrPtrTy,
2086 CGM.VoidPtrPtrTy,
2087 CGM.SizeTy->getPointerTo(),
2088 CGM.Int32Ty->getPointerTo()};
2089 llvm::FunctionType *FnTy =
2090 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2091 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2092 break;
2093 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002094 case OMPRTL__tgt_target_data_update: {
2095 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2096 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2097 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2098 CGM.Int32Ty,
2099 CGM.VoidPtrPtrTy,
2100 CGM.VoidPtrPtrTy,
2101 CGM.SizeTy->getPointerTo(),
2102 CGM.Int32Ty->getPointerTo()};
2103 llvm::FunctionType *FnTy =
2104 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2105 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2106 break;
2107 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002108 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002109 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002110 return RTLFn;
2111}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002112
Alexander Musman21212e42015-03-13 10:38:23 +00002113llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2114 bool IVSigned) {
2115 assert((IVSize == 32 || IVSize == 64) &&
2116 "IV size is not compatible with the omp runtime");
2117 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2118 : "__kmpc_for_static_init_4u")
2119 : (IVSigned ? "__kmpc_for_static_init_8"
2120 : "__kmpc_for_static_init_8u");
2121 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2122 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2123 llvm::Type *TypeParams[] = {
2124 getIdentTyPointerTy(), // loc
2125 CGM.Int32Ty, // tid
2126 CGM.Int32Ty, // schedtype
2127 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2128 PtrTy, // p_lower
2129 PtrTy, // p_upper
2130 PtrTy, // p_stride
2131 ITy, // incr
2132 ITy // chunk
2133 };
2134 llvm::FunctionType *FnTy =
2135 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2136 return CGM.CreateRuntimeFunction(FnTy, Name);
2137}
2138
Alexander Musman92bdaab2015-03-12 13:37:50 +00002139llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2140 bool IVSigned) {
2141 assert((IVSize == 32 || IVSize == 64) &&
2142 "IV size is not compatible with the omp runtime");
2143 auto Name =
2144 IVSize == 32
2145 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2146 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2147 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2148 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2149 CGM.Int32Ty, // tid
2150 CGM.Int32Ty, // schedtype
2151 ITy, // lower
2152 ITy, // upper
2153 ITy, // stride
2154 ITy // chunk
2155 };
2156 llvm::FunctionType *FnTy =
2157 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2158 return CGM.CreateRuntimeFunction(FnTy, Name);
2159}
2160
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002161llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2162 bool IVSigned) {
2163 assert((IVSize == 32 || IVSize == 64) &&
2164 "IV size is not compatible with the omp runtime");
2165 auto Name =
2166 IVSize == 32
2167 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2168 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2169 llvm::Type *TypeParams[] = {
2170 getIdentTyPointerTy(), // loc
2171 CGM.Int32Ty, // tid
2172 };
2173 llvm::FunctionType *FnTy =
2174 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2175 return CGM.CreateRuntimeFunction(FnTy, Name);
2176}
2177
Alexander Musman92bdaab2015-03-12 13:37:50 +00002178llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2179 bool IVSigned) {
2180 assert((IVSize == 32 || IVSize == 64) &&
2181 "IV size is not compatible with the omp runtime");
2182 auto Name =
2183 IVSize == 32
2184 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2185 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2186 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2187 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2188 llvm::Type *TypeParams[] = {
2189 getIdentTyPointerTy(), // loc
2190 CGM.Int32Ty, // tid
2191 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2192 PtrTy, // p_lower
2193 PtrTy, // p_upper
2194 PtrTy // p_stride
2195 };
2196 llvm::FunctionType *FnTy =
2197 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2198 return CGM.CreateRuntimeFunction(FnTy, Name);
2199}
2200
Alexey Bataev97720002014-11-11 04:05:39 +00002201llvm::Constant *
2202CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002203 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2204 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002205 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002206 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002207 Twine(CGM.getMangledName(VD)) + ".cache.");
2208}
2209
John McCall7f416cc2015-09-08 08:05:57 +00002210Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2211 const VarDecl *VD,
2212 Address VDAddr,
2213 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002214 if (CGM.getLangOpts().OpenMPUseTLS &&
2215 CGM.getContext().getTargetInfo().isTLSSupported())
2216 return VDAddr;
2217
John McCall7f416cc2015-09-08 08:05:57 +00002218 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002219 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002220 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2221 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002222 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2223 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002224 return Address(CGF.EmitRuntimeCall(
2225 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2226 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002227}
2228
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002229void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002230 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002231 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2232 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2233 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002234 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2235 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002236 OMPLoc);
2237 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2238 // to register constructor/destructor for variable.
2239 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002240 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2241 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002242 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002243 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002244 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002245}
2246
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002247llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002248 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002249 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002250 if (CGM.getLangOpts().OpenMPUseTLS &&
2251 CGM.getContext().getTargetInfo().isTLSSupported())
2252 return nullptr;
2253
Alexey Bataev97720002014-11-11 04:05:39 +00002254 VD = VD->getDefinition(CGM.getContext());
2255 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2256 ThreadPrivateWithDefinition.insert(VD);
2257 QualType ASTTy = VD->getType();
2258
2259 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2260 auto Init = VD->getAnyInitializer();
2261 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2262 // Generate function that re-emits the declaration's initializer into the
2263 // threadprivate copy of the variable VD
2264 CodeGenFunction CtorCGF(CGM);
2265 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002266 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2267 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002268 Args.push_back(&Dst);
2269
John McCallc56a8b32016-03-11 04:30:31 +00002270 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2271 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002272 auto FTy = CGM.getTypes().GetFunctionType(FI);
2273 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002274 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002275 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2276 Args, SourceLocation());
2277 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002278 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002279 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002280 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2281 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2282 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002283 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2284 /*IsInitializer=*/true);
2285 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002286 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002287 CGM.getContext().VoidPtrTy, Dst.getLocation());
2288 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2289 CtorCGF.FinishFunction();
2290 Ctor = Fn;
2291 }
2292 if (VD->getType().isDestructedType() != QualType::DK_none) {
2293 // Generate function that emits destructor call for the threadprivate copy
2294 // of the variable VD
2295 CodeGenFunction DtorCGF(CGM);
2296 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002297 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2298 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002299 Args.push_back(&Dst);
2300
John McCallc56a8b32016-03-11 04:30:31 +00002301 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2302 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002303 auto FTy = CGM.getTypes().GetFunctionType(FI);
2304 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002305 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002306 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002307 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2308 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002309 // Create a scope with an artificial location for the body of this function.
2310 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002311 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2312 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002313 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2314 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002315 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2316 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2317 DtorCGF.FinishFunction();
2318 Dtor = Fn;
2319 }
2320 // Do not emit init function if it is not required.
2321 if (!Ctor && !Dtor)
2322 return nullptr;
2323
2324 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2325 auto CopyCtorTy =
2326 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2327 /*isVarArg=*/false)->getPointerTo();
2328 // Copying constructor for the threadprivate variable.
2329 // Must be NULL - reserved by runtime, but currently it requires that this
2330 // parameter is always NULL. Otherwise it fires assertion.
2331 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2332 if (Ctor == nullptr) {
2333 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2334 /*isVarArg=*/false)->getPointerTo();
2335 Ctor = llvm::Constant::getNullValue(CtorTy);
2336 }
2337 if (Dtor == nullptr) {
2338 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2339 /*isVarArg=*/false)->getPointerTo();
2340 Dtor = llvm::Constant::getNullValue(DtorTy);
2341 }
2342 if (!CGF) {
2343 auto InitFunctionTy =
2344 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2345 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002346 InitFunctionTy, ".__omp_threadprivate_init_.",
2347 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002348 CodeGenFunction InitCGF(CGM);
2349 FunctionArgList ArgList;
2350 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2351 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2352 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002353 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002354 InitCGF.FinishFunction();
2355 return InitFunction;
2356 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002357 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002358 }
2359 return nullptr;
2360}
2361
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002362Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2363 QualType VarType,
2364 StringRef Name) {
2365 llvm::Twine VarName(Name, ".artificial.");
2366 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2367 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2368 llvm::Value *Args[] = {
2369 emitUpdateLocation(CGF, SourceLocation()),
2370 getThreadID(CGF, SourceLocation()),
2371 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2372 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2373 /*IsSigned=*/false),
2374 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2375 return Address(
2376 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2377 CGF.EmitRuntimeCall(
2378 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2379 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2380 CGM.getPointerAlign());
2381}
2382
Alexey Bataev1d677132015-04-22 13:57:31 +00002383/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2384/// function. Here is the logic:
2385/// if (Cond) {
2386/// ThenGen();
2387/// } else {
2388/// ElseGen();
2389/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002390void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2391 const RegionCodeGenTy &ThenGen,
2392 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002393 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2394
2395 // If the condition constant folds and can be elided, try to avoid emitting
2396 // the condition and the dead arm of the if/else.
2397 bool CondConstant;
2398 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002399 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002400 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002401 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002402 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002403 return;
2404 }
2405
2406 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2407 // emit the conditional branch.
2408 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2409 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2410 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2411 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2412
2413 // Emit the 'then' code.
2414 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002415 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002416 CGF.EmitBranch(ContBlock);
2417 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002418 // There is no need to emit line number for unconditional branch.
2419 (void)ApplyDebugLocation::CreateEmpty(CGF);
2420 CGF.EmitBlock(ElseBlock);
2421 ElseGen(CGF);
2422 // There is no need to emit line number for unconditional branch.
2423 (void)ApplyDebugLocation::CreateEmpty(CGF);
2424 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002425 // Emit the continuation block for code after the if.
2426 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002427}
2428
Alexey Bataev1d677132015-04-22 13:57:31 +00002429void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2430 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002431 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002432 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002433 if (!CGF.HaveInsertPoint())
2434 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002435 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002436 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2437 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002438 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002439 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002440 llvm::Value *Args[] = {
2441 RTLoc,
2442 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002443 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002444 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2445 RealArgs.append(std::begin(Args), std::end(Args));
2446 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2447
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002448 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002449 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2450 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002451 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2452 PrePostActionTy &) {
2453 auto &RT = CGF.CGM.getOpenMPRuntime();
2454 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002455 // Build calls:
2456 // __kmpc_serialized_parallel(&Loc, GTid);
2457 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002458 CGF.EmitRuntimeCall(
2459 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002460
Alexey Bataev1d677132015-04-22 13:57:31 +00002461 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002462 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002463 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002464 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2465 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002466 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002467 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2468 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2469 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2470 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002471 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002472
Alexey Bataev1d677132015-04-22 13:57:31 +00002473 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002474 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002475 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002476 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2477 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002478 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002479 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002480 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002481 else {
2482 RegionCodeGenTy ThenRCG(ThenGen);
2483 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002484 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002485}
2486
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002487// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002488// thread-ID variable (it is passed in a first argument of the outlined function
2489// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2490// regular serial code region, get thread ID by calling kmp_int32
2491// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2492// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002493Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2494 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002495 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002496 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002497 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002498 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002499
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002500 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002501 auto Int32Ty =
2502 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2503 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2504 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002505 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002506
2507 return ThreadIDTemp;
2508}
2509
Alexey Bataev97720002014-11-11 04:05:39 +00002510llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002511CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002512 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002513 SmallString<256> Buffer;
2514 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002515 Out << Name;
2516 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002517 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2518 if (Elem.second) {
2519 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002520 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002521 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002522 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002523
David Blaikie13156b62014-11-19 03:06:06 +00002524 return Elem.second = new llvm::GlobalVariable(
2525 CGM.getModule(), Ty, /*IsConstant*/ false,
2526 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2527 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002528}
2529
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002530llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002531 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002532 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002533}
2534
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002535namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002536/// Common pre(post)-action for different OpenMP constructs.
2537class CommonActionTy final : public PrePostActionTy {
2538 llvm::Value *EnterCallee;
2539 ArrayRef<llvm::Value *> EnterArgs;
2540 llvm::Value *ExitCallee;
2541 ArrayRef<llvm::Value *> ExitArgs;
2542 bool Conditional;
2543 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002544
2545public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002546 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2547 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2548 bool Conditional = false)
2549 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2550 ExitArgs(ExitArgs), Conditional(Conditional) {}
2551 void Enter(CodeGenFunction &CGF) override {
2552 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2553 if (Conditional) {
2554 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2555 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2556 ContBlock = CGF.createBasicBlock("omp_if.end");
2557 // Generate the branch (If-stmt)
2558 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2559 CGF.EmitBlock(ThenBlock);
2560 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002561 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002562 void Done(CodeGenFunction &CGF) {
2563 // Emit the rest of blocks/branches
2564 CGF.EmitBranch(ContBlock);
2565 CGF.EmitBlock(ContBlock, true);
2566 }
2567 void Exit(CodeGenFunction &CGF) override {
2568 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002569 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002570};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002571} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002572
2573void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2574 StringRef CriticalName,
2575 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002576 SourceLocation Loc, const Expr *Hint) {
2577 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002578 // CriticalOpGen();
2579 // __kmpc_end_critical(ident_t *, gtid, Lock);
2580 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002581 if (!CGF.HaveInsertPoint())
2582 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002583 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2584 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002585 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2586 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002587 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002588 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2589 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2590 }
2591 CommonActionTy Action(
2592 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2593 : OMPRTL__kmpc_critical),
2594 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2595 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002596 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002597}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002598
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002599void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002600 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002601 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002602 if (!CGF.HaveInsertPoint())
2603 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002604 // if(__kmpc_master(ident_t *, gtid)) {
2605 // MasterOpGen();
2606 // __kmpc_end_master(ident_t *, gtid);
2607 // }
2608 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002609 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002610 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2611 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2612 /*Conditional=*/true);
2613 MasterOpGen.setAction(Action);
2614 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2615 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002616}
2617
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002618void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2619 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002620 if (!CGF.HaveInsertPoint())
2621 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002622 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2623 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002624 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002625 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002626 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002627 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2628 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002629}
2630
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002631void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2632 const RegionCodeGenTy &TaskgroupOpGen,
2633 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002634 if (!CGF.HaveInsertPoint())
2635 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002636 // __kmpc_taskgroup(ident_t *, gtid);
2637 // TaskgroupOpGen();
2638 // __kmpc_end_taskgroup(ident_t *, gtid);
2639 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002640 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2641 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2642 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2643 Args);
2644 TaskgroupOpGen.setAction(Action);
2645 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002646}
2647
John McCall7f416cc2015-09-08 08:05:57 +00002648/// Given an array of pointers to variables, project the address of a
2649/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002650static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2651 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002652 // Pull out the pointer to the variable.
2653 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002654 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002655 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2656
2657 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002658 Addr = CGF.Builder.CreateElementBitCast(
2659 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002660 return Addr;
2661}
2662
Alexey Bataeva63048e2015-03-23 06:18:07 +00002663static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002664 CodeGenModule &CGM, llvm::Type *ArgsType,
2665 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2666 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002667 auto &C = CGM.getContext();
2668 // void copy_func(void *LHSArg, void *RHSArg);
2669 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002670 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2671 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002672 Args.push_back(&LHSArg);
2673 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002674 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002675 auto *Fn = llvm::Function::Create(
2676 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2677 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002678 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002679 CodeGenFunction CGF(CGM);
2680 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002681 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002682 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002683 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2684 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2685 ArgsType), CGF.getPointerAlign());
2686 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2687 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2688 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002689 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2690 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2691 // ...
2692 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002693 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002694 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2695 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2696
2697 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2698 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2699
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002700 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2701 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002702 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002703 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002704 CGF.FinishFunction();
2705 return Fn;
2706}
2707
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002708void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002709 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002710 SourceLocation Loc,
2711 ArrayRef<const Expr *> CopyprivateVars,
2712 ArrayRef<const Expr *> SrcExprs,
2713 ArrayRef<const Expr *> DstExprs,
2714 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002715 if (!CGF.HaveInsertPoint())
2716 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002717 assert(CopyprivateVars.size() == SrcExprs.size() &&
2718 CopyprivateVars.size() == DstExprs.size() &&
2719 CopyprivateVars.size() == AssignmentOps.size());
2720 auto &C = CGM.getContext();
2721 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002722 // if(__kmpc_single(ident_t *, gtid)) {
2723 // SingleOpGen();
2724 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002725 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002726 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002727 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2728 // <copy_func>, did_it);
2729
John McCall7f416cc2015-09-08 08:05:57 +00002730 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002731 if (!CopyprivateVars.empty()) {
2732 // int32 did_it = 0;
2733 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2734 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002735 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002736 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002737 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002738 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002739 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2740 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2741 /*Conditional=*/true);
2742 SingleOpGen.setAction(Action);
2743 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2744 if (DidIt.isValid()) {
2745 // did_it = 1;
2746 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2747 }
2748 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002749 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2750 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002751 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002752 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2753 auto CopyprivateArrayTy =
2754 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2755 /*IndexTypeQuals=*/0);
2756 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002757 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002758 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2759 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002760 Address Elem = CGF.Builder.CreateConstArrayGEP(
2761 CopyprivateList, I, CGF.getPointerSize());
2762 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002763 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002764 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2765 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002766 }
2767 // Build function that copies private values from single region to all other
2768 // threads in the corresponding parallel region.
2769 auto *CpyFn = emitCopyprivateCopyFunction(
2770 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002771 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002772 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002773 Address CL =
2774 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2775 CGF.VoidPtrTy);
2776 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002777 llvm::Value *Args[] = {
2778 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2779 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002780 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002781 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002782 CpyFn, // void (*) (void *, void *) <copy_func>
2783 DidItVal // i32 did_it
2784 };
2785 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2786 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002787}
2788
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002789void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2790 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002791 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002792 if (!CGF.HaveInsertPoint())
2793 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002794 // __kmpc_ordered(ident_t *, gtid);
2795 // OrderedOpGen();
2796 // __kmpc_end_ordered(ident_t *, gtid);
2797 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002798 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002799 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002800 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2801 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2802 Args);
2803 OrderedOpGen.setAction(Action);
2804 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2805 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002806 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002807 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002808}
2809
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002810void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002811 OpenMPDirectiveKind Kind, bool EmitChecks,
2812 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002813 if (!CGF.HaveInsertPoint())
2814 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002815 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002816 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002817 unsigned Flags;
2818 if (Kind == OMPD_for)
2819 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2820 else if (Kind == OMPD_sections)
2821 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2822 else if (Kind == OMPD_single)
2823 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2824 else if (Kind == OMPD_barrier)
2825 Flags = OMP_IDENT_BARRIER_EXPL;
2826 else
2827 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002828 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2829 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002830 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2831 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002832 if (auto *OMPRegionInfo =
2833 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002834 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002835 auto *Result = CGF.EmitRuntimeCall(
2836 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002837 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002838 // if (__kmpc_cancel_barrier()) {
2839 // exit from construct;
2840 // }
2841 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2842 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2843 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2844 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2845 CGF.EmitBlock(ExitBB);
2846 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002847 auto CancelDestination =
2848 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002849 CGF.EmitBranchThroughCleanup(CancelDestination);
2850 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2851 }
2852 return;
2853 }
2854 }
2855 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002856}
2857
Alexander Musmanc6388682014-12-15 07:07:06 +00002858/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2859static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002860 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002861 switch (ScheduleKind) {
2862 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002863 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2864 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002865 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002866 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002867 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002868 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002869 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002870 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2871 case OMPC_SCHEDULE_auto:
2872 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002873 case OMPC_SCHEDULE_unknown:
2874 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002875 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002876 }
2877 llvm_unreachable("Unexpected runtime schedule");
2878}
2879
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002880/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2881static OpenMPSchedType
2882getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2883 // only static is allowed for dist_schedule
2884 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2885}
2886
Alexander Musmanc6388682014-12-15 07:07:06 +00002887bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2888 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002889 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002890 return Schedule == OMP_sch_static;
2891}
2892
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002893bool CGOpenMPRuntime::isStaticNonchunked(
2894 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2895 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2896 return Schedule == OMP_dist_sch_static;
2897}
2898
2899
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002900bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002901 auto Schedule =
2902 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002903 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2904 return Schedule != OMP_sch_static;
2905}
2906
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002907static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2908 OpenMPScheduleClauseModifier M1,
2909 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002910 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002911 switch (M1) {
2912 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002913 Modifier = OMP_sch_modifier_monotonic;
2914 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002915 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002916 Modifier = OMP_sch_modifier_nonmonotonic;
2917 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002918 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002919 if (Schedule == OMP_sch_static_chunked)
2920 Schedule = OMP_sch_static_balanced_chunked;
2921 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002922 case OMPC_SCHEDULE_MODIFIER_last:
2923 case OMPC_SCHEDULE_MODIFIER_unknown:
2924 break;
2925 }
2926 switch (M2) {
2927 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002928 Modifier = OMP_sch_modifier_monotonic;
2929 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002930 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002931 Modifier = OMP_sch_modifier_nonmonotonic;
2932 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002933 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002934 if (Schedule == OMP_sch_static_chunked)
2935 Schedule = OMP_sch_static_balanced_chunked;
2936 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002937 case OMPC_SCHEDULE_MODIFIER_last:
2938 case OMPC_SCHEDULE_MODIFIER_unknown:
2939 break;
2940 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002941 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002942}
2943
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002944void CGOpenMPRuntime::emitForDispatchInit(
2945 CodeGenFunction &CGF, SourceLocation Loc,
2946 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2947 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002948 if (!CGF.HaveInsertPoint())
2949 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002950 OpenMPSchedType Schedule = getRuntimeSchedule(
2951 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002952 assert(Ordered ||
2953 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002954 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2955 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002956 // Call __kmpc_dispatch_init(
2957 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2958 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2959 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002960
John McCall7f416cc2015-09-08 08:05:57 +00002961 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002962 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2963 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002964 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002965 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2966 CGF.Builder.getInt32(addMonoNonMonoModifier(
2967 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002968 DispatchValues.LB, // Lower
2969 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002970 CGF.Builder.getIntN(IVSize, 1), // Stride
2971 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002972 };
2973 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2974}
2975
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002976static void emitForStaticInitCall(
2977 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2978 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2979 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002980 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002981 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002982 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002983
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002984 assert(!Values.Ordered);
2985 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2986 Schedule == OMP_sch_static_balanced_chunked ||
2987 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2988 Schedule == OMP_dist_sch_static ||
2989 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002990
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002991 // Call __kmpc_for_static_init(
2992 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2993 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2994 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2995 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2996 llvm::Value *Chunk = Values.Chunk;
2997 if (Chunk == nullptr) {
2998 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2999 Schedule == OMP_dist_sch_static) &&
3000 "expected static non-chunked schedule");
3001 // If the Chunk was not specified in the clause - use default value 1.
3002 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3003 } else {
3004 assert((Schedule == OMP_sch_static_chunked ||
3005 Schedule == OMP_sch_static_balanced_chunked ||
3006 Schedule == OMP_ord_static_chunked ||
3007 Schedule == OMP_dist_sch_static_chunked) &&
3008 "expected static chunked schedule");
3009 }
3010 llvm::Value *Args[] = {
3011 UpdateLocation,
3012 ThreadId,
3013 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3014 M2)), // Schedule type
3015 Values.IL.getPointer(), // &isLastIter
3016 Values.LB.getPointer(), // &LB
3017 Values.UB.getPointer(), // &UB
3018 Values.ST.getPointer(), // &Stride
3019 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3020 Chunk // Chunk
3021 };
3022 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003023}
3024
John McCall7f416cc2015-09-08 08:05:57 +00003025void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3026 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003027 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003028 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003029 const StaticRTInput &Values) {
3030 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3031 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3032 assert(isOpenMPWorksharingDirective(DKind) &&
3033 "Expected loop-based or sections-based directive.");
3034 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3035 isOpenMPLoopDirective(DKind)
3036 ? OMP_IDENT_WORK_LOOP
3037 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003038 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003039 auto *StaticInitFunction =
3040 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003041 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003042 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003043}
John McCall7f416cc2015-09-08 08:05:57 +00003044
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003045void CGOpenMPRuntime::emitDistributeStaticInit(
3046 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003047 OpenMPDistScheduleClauseKind SchedKind,
3048 const CGOpenMPRuntime::StaticRTInput &Values) {
3049 OpenMPSchedType ScheduleNum =
3050 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3051 auto *UpdatedLocation =
3052 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003053 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003054 auto *StaticInitFunction =
3055 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003056 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3057 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003058 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003059}
3060
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003061void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003062 SourceLocation Loc,
3063 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003064 if (!CGF.HaveInsertPoint())
3065 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003066 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003067 llvm::Value *Args[] = {
3068 emitUpdateLocation(CGF, Loc,
3069 isOpenMPDistributeDirective(DKind)
3070 ? OMP_IDENT_WORK_DISTRIBUTE
3071 : isOpenMPLoopDirective(DKind)
3072 ? OMP_IDENT_WORK_LOOP
3073 : OMP_IDENT_WORK_SECTIONS),
3074 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003075 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3076 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003077}
3078
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003079void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3080 SourceLocation Loc,
3081 unsigned IVSize,
3082 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003083 if (!CGF.HaveInsertPoint())
3084 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003085 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003086 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003087 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3088}
3089
Alexander Musman92bdaab2015-03-12 13:37:50 +00003090llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3091 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003092 bool IVSigned, Address IL,
3093 Address LB, Address UB,
3094 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003095 // Call __kmpc_dispatch_next(
3096 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3097 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3098 // kmp_int[32|64] *p_stride);
3099 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003100 emitUpdateLocation(CGF, Loc),
3101 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003102 IL.getPointer(), // &isLastIter
3103 LB.getPointer(), // &Lower
3104 UB.getPointer(), // &Upper
3105 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003106 };
3107 llvm::Value *Call =
3108 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3109 return CGF.EmitScalarConversion(
3110 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003111 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003112}
3113
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003114void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3115 llvm::Value *NumThreads,
3116 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003117 if (!CGF.HaveInsertPoint())
3118 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003119 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3120 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003121 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003122 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003123 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3124 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003125}
3126
Alexey Bataev7f210c62015-06-18 13:40:03 +00003127void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3128 OpenMPProcBindClauseKind ProcBind,
3129 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003130 if (!CGF.HaveInsertPoint())
3131 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003132 // Constants for proc bind value accepted by the runtime.
3133 enum ProcBindTy {
3134 ProcBindFalse = 0,
3135 ProcBindTrue,
3136 ProcBindMaster,
3137 ProcBindClose,
3138 ProcBindSpread,
3139 ProcBindIntel,
3140 ProcBindDefault
3141 } RuntimeProcBind;
3142 switch (ProcBind) {
3143 case OMPC_PROC_BIND_master:
3144 RuntimeProcBind = ProcBindMaster;
3145 break;
3146 case OMPC_PROC_BIND_close:
3147 RuntimeProcBind = ProcBindClose;
3148 break;
3149 case OMPC_PROC_BIND_spread:
3150 RuntimeProcBind = ProcBindSpread;
3151 break;
3152 case OMPC_PROC_BIND_unknown:
3153 llvm_unreachable("Unsupported proc_bind value.");
3154 }
3155 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3156 llvm::Value *Args[] = {
3157 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3158 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3159 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3160}
3161
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003162void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3163 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003164 if (!CGF.HaveInsertPoint())
3165 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003166 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003167 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3168 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003169}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003170
Alexey Bataev62b63b12015-03-10 07:28:44 +00003171namespace {
3172/// \brief Indexes of fields for type kmp_task_t.
3173enum KmpTaskTFields {
3174 /// \brief List of shared variables.
3175 KmpTaskTShareds,
3176 /// \brief Task routine.
3177 KmpTaskTRoutine,
3178 /// \brief Partition id for the untied tasks.
3179 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003180 /// Function with call of destructors for private variables.
3181 Data1,
3182 /// Task priority.
3183 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003184 /// (Taskloops only) Lower bound.
3185 KmpTaskTLowerBound,
3186 /// (Taskloops only) Upper bound.
3187 KmpTaskTUpperBound,
3188 /// (Taskloops only) Stride.
3189 KmpTaskTStride,
3190 /// (Taskloops only) Is last iteration flag.
3191 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003192 /// (Taskloops only) Reduction data.
3193 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003194};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003195} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003196
Samuel Antaoee8fb302016-01-06 13:42:12 +00003197bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3198 // FIXME: Add other entries type when they become supported.
3199 return OffloadEntriesTargetRegion.empty();
3200}
3201
3202/// \brief Initialize target region entry.
3203void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3204 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3205 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003206 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003207 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3208 "only required for the device "
3209 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003210 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003211 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3212 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003213 ++OffloadingEntriesNum;
3214}
3215
3216void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3217 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3218 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003219 llvm::Constant *Addr, llvm::Constant *ID,
3220 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003221 // If we are emitting code for a target, the entry is already initialized,
3222 // only has to be registered.
3223 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003224 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003225 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003226 auto &Entry =
3227 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003228 assert(Entry.isValid() && "Entry not initialized!");
3229 Entry.setAddress(Addr);
3230 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003231 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003232 return;
3233 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003234 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003235 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003236 }
3237}
3238
3239bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003240 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3241 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003242 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3243 if (PerDevice == OffloadEntriesTargetRegion.end())
3244 return false;
3245 auto PerFile = PerDevice->second.find(FileID);
3246 if (PerFile == PerDevice->second.end())
3247 return false;
3248 auto PerParentName = PerFile->second.find(ParentName);
3249 if (PerParentName == PerFile->second.end())
3250 return false;
3251 auto PerLine = PerParentName->second.find(LineNum);
3252 if (PerLine == PerParentName->second.end())
3253 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003254 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003255 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003256 return false;
3257 return true;
3258}
3259
3260void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3261 const OffloadTargetRegionEntryInfoActTy &Action) {
3262 // Scan all target region entries and perform the provided action.
3263 for (auto &D : OffloadEntriesTargetRegion)
3264 for (auto &F : D.second)
3265 for (auto &P : F.second)
3266 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003267 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003268}
3269
3270/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3271/// \a Codegen. This is used to emit the two functions that register and
3272/// unregister the descriptor of the current compilation unit.
3273static llvm::Function *
3274createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3275 const RegionCodeGenTy &Codegen) {
3276 auto &C = CGM.getContext();
3277 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003278 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003279 Args.push_back(&DummyPtr);
3280
3281 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003282 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003283 auto FTy = CGM.getTypes().GetFunctionType(FI);
3284 auto *Fn =
3285 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3286 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3287 Codegen(CGF);
3288 CGF.FinishFunction();
3289 return Fn;
3290}
3291
3292llvm::Function *
3293CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3294
3295 // If we don't have entries or if we are emitting code for the device, we
3296 // don't need to do anything.
3297 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3298 return nullptr;
3299
3300 auto &M = CGM.getModule();
3301 auto &C = CGM.getContext();
3302
3303 // Get list of devices we care about
3304 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3305
3306 // We should be creating an offloading descriptor only if there are devices
3307 // specified.
3308 assert(!Devices.empty() && "No OpenMP offloading devices??");
3309
3310 // Create the external variables that will point to the begin and end of the
3311 // host entries section. These will be defined by the linker.
3312 auto *OffloadEntryTy =
3313 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3314 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3315 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003316 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003317 ".omp_offloading.entries_begin");
3318 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3319 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003320 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003321 ".omp_offloading.entries_end");
3322
3323 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003324 auto *DeviceImageTy = cast<llvm::StructType>(
3325 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003326 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003327 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003328
3329 for (unsigned i = 0; i < Devices.size(); ++i) {
3330 StringRef T = Devices[i].getTriple();
3331 auto *ImgBegin = new llvm::GlobalVariable(
3332 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003333 /*Initializer=*/nullptr,
3334 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003335 auto *ImgEnd = new llvm::GlobalVariable(
3336 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003337 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003338
John McCall6c9f1fdb2016-11-19 08:17:24 +00003339 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3340 Dev.add(ImgBegin);
3341 Dev.add(ImgEnd);
3342 Dev.add(HostEntriesBegin);
3343 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003344 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003345 }
3346
3347 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003348 llvm::GlobalVariable *DeviceImages =
3349 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3350 CGM.getPointerAlign(),
3351 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003352 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003353
3354 // This is a Zero array to be used in the creation of the constant expressions
3355 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3356 llvm::Constant::getNullValue(CGM.Int32Ty)};
3357
3358 // Create the target region descriptor.
3359 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3360 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003361 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003362 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3363 DescInit.addInt(CGM.Int32Ty, Devices.size());
3364 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3365 DeviceImages,
3366 Index));
3367 DescInit.add(HostEntriesBegin);
3368 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003369
John McCall6c9f1fdb2016-11-19 08:17:24 +00003370 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3371 CGM.getPointerAlign(),
3372 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003373
3374 // Emit code to register or unregister the descriptor at execution
3375 // startup or closing, respectively.
3376
3377 // Create a variable to drive the registration and unregistration of the
3378 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3379 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3380 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003381 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003382
3383 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003384 CGM, ".omp_offloading.descriptor_unreg",
3385 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003386 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3387 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003388 });
3389 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003390 CGM, ".omp_offloading.descriptor_reg",
3391 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003392 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3393 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003394 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3395 });
George Rokos29d0f002017-05-27 03:03:13 +00003396 if (CGM.supportsCOMDAT()) {
3397 // It is sufficient to call registration function only once, so create a
3398 // COMDAT group for registration/unregistration functions and associated
3399 // data. That would reduce startup time and code size. Registration
3400 // function serves as a COMDAT group key.
3401 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3402 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3403 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3404 RegFn->setComdat(ComdatKey);
3405 UnRegFn->setComdat(ComdatKey);
3406 DeviceImages->setComdat(ComdatKey);
3407 Desc->setComdat(ComdatKey);
3408 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003409 return RegFn;
3410}
3411
Samuel Antao2de62b02016-02-13 23:35:10 +00003412void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003413 llvm::Constant *Addr, uint64_t Size,
3414 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003415 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003416 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3417 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3418 llvm::LLVMContext &C = CGM.getModule().getContext();
3419 llvm::Module &M = CGM.getModule();
3420
3421 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003422 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003423
3424 // Create constant string with the name.
3425 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3426
3427 llvm::GlobalVariable *Str =
3428 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3429 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3430 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003431 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003432 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3433
John McCall6c9f1fdb2016-11-19 08:17:24 +00003434 // We can't have any padding between symbols, so we need to have 1-byte
3435 // alignment.
3436 auto Align = CharUnits::fromQuantity(1);
3437
Samuel Antaoee8fb302016-01-06 13:42:12 +00003438 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003439 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003440 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3441 EntryInit.add(AddrPtr);
3442 EntryInit.add(StrPtr);
3443 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003444 EntryInit.addInt(CGM.Int32Ty, Flags);
3445 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003446 llvm::GlobalVariable *Entry =
3447 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3448 Align,
3449 /*constant*/ true,
3450 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003451
3452 // The entry has to be created in the section the linker expects it to be.
3453 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003454}
3455
3456void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3457 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003458 // can easily figure out what to emit. The produced metadata looks like
3459 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003460 //
3461 // !omp_offload.info = !{!1, ...}
3462 //
3463 // Right now we only generate metadata for function that contain target
3464 // regions.
3465
3466 // If we do not have entries, we dont need to do anything.
3467 if (OffloadEntriesInfoManager.empty())
3468 return;
3469
3470 llvm::Module &M = CGM.getModule();
3471 llvm::LLVMContext &C = M.getContext();
3472 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3473 OrderedEntries(OffloadEntriesInfoManager.size());
3474
3475 // Create the offloading info metadata node.
3476 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3477
Simon Pilgrim2c518802017-03-30 14:13:19 +00003478 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003479 auto getMDInt = [&](unsigned v) {
3480 return llvm::ConstantAsMetadata::get(
3481 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3482 };
3483
3484 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3485
3486 // Create function that emits metadata for each target region entry;
3487 auto &&TargetRegionMetadataEmitter = [&](
3488 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003489 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3490 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3491 // Generate metadata for target regions. Each entry of this metadata
3492 // contains:
3493 // - Entry 0 -> Kind of this type of metadata (0).
3494 // - Entry 1 -> Device ID of the file where the entry was identified.
3495 // - Entry 2 -> File ID of the file where the entry was identified.
3496 // - Entry 3 -> Mangled name of the function where the entry was identified.
3497 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003498 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003499 // The first element of the metadata node is the kind.
3500 Ops.push_back(getMDInt(E.getKind()));
3501 Ops.push_back(getMDInt(DeviceID));
3502 Ops.push_back(getMDInt(FileID));
3503 Ops.push_back(getMDString(ParentName));
3504 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003505 Ops.push_back(getMDInt(E.getOrder()));
3506
3507 // Save this entry in the right position of the ordered entries array.
3508 OrderedEntries[E.getOrder()] = &E;
3509
3510 // Add metadata to the named metadata node.
3511 MD->addOperand(llvm::MDNode::get(C, Ops));
3512 };
3513
3514 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3515 TargetRegionMetadataEmitter);
3516
3517 for (auto *E : OrderedEntries) {
3518 assert(E && "All ordered entries must exist!");
3519 if (auto *CE =
3520 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3521 E)) {
3522 assert(CE->getID() && CE->getAddress() &&
3523 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003524 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003525 } else
3526 llvm_unreachable("Unsupported entry kind.");
3527 }
3528}
3529
3530/// \brief Loads all the offload entries information from the host IR
3531/// metadata.
3532void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3533 // If we are in target mode, load the metadata from the host IR. This code has
3534 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3535
3536 if (!CGM.getLangOpts().OpenMPIsDevice)
3537 return;
3538
3539 if (CGM.getLangOpts().OMPHostIRFile.empty())
3540 return;
3541
3542 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3543 if (Buf.getError())
3544 return;
3545
3546 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003547 auto ME = expectedToErrorOrAndEmitErrors(
3548 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003549
3550 if (ME.getError())
3551 return;
3552
3553 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3554 if (!MD)
3555 return;
3556
3557 for (auto I : MD->operands()) {
3558 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3559
3560 auto getMDInt = [&](unsigned Idx) {
3561 llvm::ConstantAsMetadata *V =
3562 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3563 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3564 };
3565
3566 auto getMDString = [&](unsigned Idx) {
3567 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3568 return V->getString();
3569 };
3570
3571 switch (getMDInt(0)) {
3572 default:
3573 llvm_unreachable("Unexpected metadata!");
3574 break;
3575 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3576 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3577 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3578 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3579 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003580 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003581 break;
3582 }
3583 }
3584}
3585
Alexey Bataev62b63b12015-03-10 07:28:44 +00003586void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3587 if (!KmpRoutineEntryPtrTy) {
3588 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3589 auto &C = CGM.getContext();
3590 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3591 FunctionProtoType::ExtProtoInfo EPI;
3592 KmpRoutineEntryPtrQTy = C.getPointerType(
3593 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3594 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3595 }
3596}
3597
Alexey Bataevc71a4092015-09-11 10:29:41 +00003598static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3599 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003600 auto *Field = FieldDecl::Create(
3601 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3602 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3603 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3604 Field->setAccess(AS_public);
3605 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003606 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003607}
3608
Samuel Antaoee8fb302016-01-06 13:42:12 +00003609QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3610
3611 // Make sure the type of the entry is already created. This is the type we
3612 // have to create:
3613 // struct __tgt_offload_entry{
3614 // void *addr; // Pointer to the offload entry info.
3615 // // (function or global)
3616 // char *name; // Name of the function or global.
3617 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003618 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3619 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003620 // };
3621 if (TgtOffloadEntryQTy.isNull()) {
3622 ASTContext &C = CGM.getContext();
3623 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3624 RD->startDefinition();
3625 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3626 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3627 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003628 addFieldToRecordDecl(
3629 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3630 addFieldToRecordDecl(
3631 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003632 RD->completeDefinition();
3633 TgtOffloadEntryQTy = C.getRecordType(RD);
3634 }
3635 return TgtOffloadEntryQTy;
3636}
3637
3638QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3639 // These are the types we need to build:
3640 // struct __tgt_device_image{
3641 // void *ImageStart; // Pointer to the target code start.
3642 // void *ImageEnd; // Pointer to the target code end.
3643 // // We also add the host entries to the device image, as it may be useful
3644 // // for the target runtime to have access to that information.
3645 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3646 // // the entries.
3647 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3648 // // entries (non inclusive).
3649 // };
3650 if (TgtDeviceImageQTy.isNull()) {
3651 ASTContext &C = CGM.getContext();
3652 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3653 RD->startDefinition();
3654 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3655 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3656 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3657 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3658 RD->completeDefinition();
3659 TgtDeviceImageQTy = C.getRecordType(RD);
3660 }
3661 return TgtDeviceImageQTy;
3662}
3663
3664QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3665 // struct __tgt_bin_desc{
3666 // int32_t NumDevices; // Number of devices supported.
3667 // __tgt_device_image *DeviceImages; // Arrays of device images
3668 // // (one per device).
3669 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3670 // // entries.
3671 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3672 // // entries (non inclusive).
3673 // };
3674 if (TgtBinaryDescriptorQTy.isNull()) {
3675 ASTContext &C = CGM.getContext();
3676 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3677 RD->startDefinition();
3678 addFieldToRecordDecl(
3679 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3680 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3681 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3682 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3683 RD->completeDefinition();
3684 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3685 }
3686 return TgtBinaryDescriptorQTy;
3687}
3688
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003689namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003690struct PrivateHelpersTy {
3691 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3692 const VarDecl *PrivateElemInit)
3693 : Original(Original), PrivateCopy(PrivateCopy),
3694 PrivateElemInit(PrivateElemInit) {}
3695 const VarDecl *Original;
3696 const VarDecl *PrivateCopy;
3697 const VarDecl *PrivateElemInit;
3698};
3699typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003700} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003701
Alexey Bataev9e034042015-05-05 04:05:12 +00003702static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003703createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003704 if (!Privates.empty()) {
3705 auto &C = CGM.getContext();
3706 // Build struct .kmp_privates_t. {
3707 // /* private vars */
3708 // };
3709 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3710 RD->startDefinition();
3711 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003712 auto *VD = Pair.second.Original;
3713 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003714 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003715 auto *FD = addFieldToRecordDecl(C, RD, Type);
3716 if (VD->hasAttrs()) {
3717 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3718 E(VD->getAttrs().end());
3719 I != E; ++I)
3720 FD->addAttr(*I);
3721 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003722 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003723 RD->completeDefinition();
3724 return RD;
3725 }
3726 return nullptr;
3727}
3728
Alexey Bataev9e034042015-05-05 04:05:12 +00003729static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003730createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3731 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003732 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003733 auto &C = CGM.getContext();
3734 // Build struct kmp_task_t {
3735 // void * shareds;
3736 // kmp_routine_entry_t routine;
3737 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003738 // kmp_cmplrdata_t data1;
3739 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003740 // For taskloops additional fields:
3741 // kmp_uint64 lb;
3742 // kmp_uint64 ub;
3743 // kmp_int64 st;
3744 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003745 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003746 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003747 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3748 UD->startDefinition();
3749 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3750 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3751 UD->completeDefinition();
3752 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003753 auto *RD = C.buildImplicitRecord("kmp_task_t");
3754 RD->startDefinition();
3755 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3756 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3757 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003758 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3759 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003760 if (isOpenMPTaskLoopDirective(Kind)) {
3761 QualType KmpUInt64Ty =
3762 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3763 QualType KmpInt64Ty =
3764 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3765 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3766 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3767 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3768 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003769 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003770 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003771 RD->completeDefinition();
3772 return RD;
3773}
3774
3775static RecordDecl *
3776createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003777 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003778 auto &C = CGM.getContext();
3779 // Build struct kmp_task_t_with_privates {
3780 // kmp_task_t task_data;
3781 // .kmp_privates_t. privates;
3782 // };
3783 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3784 RD->startDefinition();
3785 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003786 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3787 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3788 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003789 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003790 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003791}
3792
3793/// \brief Emit a proxy function which accepts kmp_task_t as the second
3794/// argument.
3795/// \code
3796/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003797/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003798/// For taskloops:
3799/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003800/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003801/// return 0;
3802/// }
3803/// \endcode
3804static llvm::Value *
3805emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003806 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3807 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003808 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003809 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3810 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003811 auto &C = CGM.getContext();
3812 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003813 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3814 ImplicitParamDecl::Other);
3815 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3816 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3817 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003818 Args.push_back(&GtidArg);
3819 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003820 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003821 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003822 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3823 auto *TaskEntry =
3824 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3825 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003826 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003827 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003828 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3829
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003830 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003831 // tt,
3832 // For taskloops:
3833 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3834 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003835 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003836 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003837 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3838 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3839 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003840 auto *KmpTaskTWithPrivatesQTyRD =
3841 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003842 LValue Base =
3843 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003844 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3845 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3846 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003847 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003848
3849 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3850 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003851 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003852 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003853 CGF.ConvertTypeForMem(SharedsPtrTy));
3854
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003855 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3856 llvm::Value *PrivatesParam;
3857 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3858 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3859 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003860 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003861 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003862 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003863
Alexey Bataev7292c292016-04-25 12:22:29 +00003864 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3865 TaskPrivatesMap,
3866 CGF.Builder
3867 .CreatePointerBitCastOrAddrSpaceCast(
3868 TDBase.getAddress(), CGF.VoidPtrTy)
3869 .getPointer()};
3870 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3871 std::end(CommonArgs));
3872 if (isOpenMPTaskLoopDirective(Kind)) {
3873 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3874 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3875 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3876 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3877 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3878 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3879 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3880 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3881 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3882 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3883 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3884 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003885 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3886 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3887 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003888 CallArgs.push_back(LBParam);
3889 CallArgs.push_back(UBParam);
3890 CallArgs.push_back(StParam);
3891 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003892 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003893 }
3894 CallArgs.push_back(SharedsParam);
3895
Alexey Bataev3c595a62017-08-14 15:01:03 +00003896 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3897 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003898 CGF.EmitStoreThroughLValue(
3899 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003900 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003901 CGF.FinishFunction();
3902 return TaskEntry;
3903}
3904
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003905static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3906 SourceLocation Loc,
3907 QualType KmpInt32Ty,
3908 QualType KmpTaskTWithPrivatesPtrQTy,
3909 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003910 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003911 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003912 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3913 ImplicitParamDecl::Other);
3914 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3915 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3916 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003917 Args.push_back(&GtidArg);
3918 Args.push_back(&TaskTypeArg);
3919 FunctionType::ExtInfo Info;
3920 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003921 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003922 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3923 auto *DestructorFn =
3924 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3925 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003926 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3927 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003928 CodeGenFunction CGF(CGM);
3929 CGF.disableDebugInfo();
3930 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3931 Args);
3932
Alexey Bataev31300ed2016-02-04 11:27:03 +00003933 LValue Base = CGF.EmitLoadOfPointerLValue(
3934 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3935 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003936 auto *KmpTaskTWithPrivatesQTyRD =
3937 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3938 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003939 Base = CGF.EmitLValueForField(Base, *FI);
3940 for (auto *Field :
3941 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3942 if (auto DtorKind = Field->getType().isDestructedType()) {
3943 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3944 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3945 }
3946 }
3947 CGF.FinishFunction();
3948 return DestructorFn;
3949}
3950
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003951/// \brief Emit a privates mapping function for correct handling of private and
3952/// firstprivate variables.
3953/// \code
3954/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3955/// **noalias priv1,..., <tyn> **noalias privn) {
3956/// *priv1 = &.privates.priv1;
3957/// ...;
3958/// *privn = &.privates.privn;
3959/// }
3960/// \endcode
3961static llvm::Value *
3962emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003963 ArrayRef<const Expr *> PrivateVars,
3964 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003965 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003966 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003967 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003968 auto &C = CGM.getContext();
3969 FunctionArgList Args;
3970 ImplicitParamDecl TaskPrivatesArg(
3971 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003972 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3973 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003974 Args.push_back(&TaskPrivatesArg);
3975 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3976 unsigned Counter = 1;
3977 for (auto *E: PrivateVars) {
3978 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003979 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3980 C.getPointerType(C.getPointerType(E->getType()))
3981 .withConst()
3982 .withRestrict(),
3983 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003984 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3985 PrivateVarsPos[VD] = Counter;
3986 ++Counter;
3987 }
3988 for (auto *E : FirstprivateVars) {
3989 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003990 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3991 C.getPointerType(C.getPointerType(E->getType()))
3992 .withConst()
3993 .withRestrict(),
3994 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003995 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3996 PrivateVarsPos[VD] = Counter;
3997 ++Counter;
3998 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003999 for (auto *E: LastprivateVars) {
4000 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004001 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4002 C.getPointerType(C.getPointerType(E->getType()))
4003 .withConst()
4004 .withRestrict(),
4005 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004006 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4007 PrivateVarsPos[VD] = Counter;
4008 ++Counter;
4009 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004010 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004011 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004012 auto *TaskPrivatesMapTy =
4013 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4014 auto *TaskPrivatesMap = llvm::Function::Create(
4015 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4016 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004017 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4018 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004019 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004020 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004021 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004022 CodeGenFunction CGF(CGM);
4023 CGF.disableDebugInfo();
4024 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4025 TaskPrivatesMapFnInfo, Args);
4026
4027 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004028 LValue Base = CGF.EmitLoadOfPointerLValue(
4029 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4030 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004031 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4032 Counter = 0;
4033 for (auto *Field : PrivatesQTyRD->fields()) {
4034 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4035 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004036 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004037 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4038 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004039 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004040 ++Counter;
4041 }
4042 CGF.FinishFunction();
4043 return TaskPrivatesMap;
4044}
4045
Alexey Bataev9e034042015-05-05 04:05:12 +00004046static int array_pod_sort_comparator(const PrivateDataTy *P1,
4047 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004048 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4049}
4050
Alexey Bataevf93095a2016-05-05 08:46:22 +00004051/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004052static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004053 const OMPExecutableDirective &D,
4054 Address KmpTaskSharedsPtr, LValue TDBase,
4055 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4056 QualType SharedsTy, QualType SharedsPtrTy,
4057 const OMPTaskDataTy &Data,
4058 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4059 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004060 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4061 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4062 LValue SrcBase;
4063 if (!Data.FirstprivateVars.empty()) {
4064 SrcBase = CGF.MakeAddrLValue(
4065 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4066 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4067 SharedsTy);
4068 }
4069 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4070 cast<CapturedStmt>(*D.getAssociatedStmt()));
4071 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4072 for (auto &&Pair : Privates) {
4073 auto *VD = Pair.second.PrivateCopy;
4074 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004075 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4076 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004077 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004078 if (auto *Elem = Pair.second.PrivateElemInit) {
4079 auto *OriginalVD = Pair.second.Original;
4080 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4081 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4082 SharedRefLValue = CGF.MakeAddrLValue(
4083 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004084 SharedRefLValue.getType(),
4085 LValueBaseInfo(AlignmentSource::Decl,
4086 SharedRefLValue.getBaseInfo().getMayAlias()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004087 QualType Type = OriginalVD->getType();
4088 if (Type->isArrayType()) {
4089 // Initialize firstprivate array.
4090 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4091 // Perform simple memcpy.
4092 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4093 SharedRefLValue.getAddress(), Type);
4094 } else {
4095 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004096 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004097 CGF.EmitOMPAggregateAssign(
4098 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4099 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4100 Address SrcElement) {
4101 // Clean up any temporaries needed by the initialization.
4102 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4103 InitScope.addPrivate(
4104 Elem, [SrcElement]() -> Address { return SrcElement; });
4105 (void)InitScope.Privatize();
4106 // Emit initialization for single element.
4107 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4108 CGF, &CapturesInfo);
4109 CGF.EmitAnyExprToMem(Init, DestElement,
4110 Init->getType().getQualifiers(),
4111 /*IsInitializer=*/false);
4112 });
4113 }
4114 } else {
4115 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4116 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4117 return SharedRefLValue.getAddress();
4118 });
4119 (void)InitScope.Privatize();
4120 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4121 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4122 /*capturedByInit=*/false);
4123 }
4124 } else
4125 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4126 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004127 ++FI;
4128 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004129}
4130
4131/// Check if duplication function is required for taskloops.
4132static bool checkInitIsRequired(CodeGenFunction &CGF,
4133 ArrayRef<PrivateDataTy> Privates) {
4134 bool InitRequired = false;
4135 for (auto &&Pair : Privates) {
4136 auto *VD = Pair.second.PrivateCopy;
4137 auto *Init = VD->getAnyInitializer();
4138 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4139 !CGF.isTrivialInitializer(Init));
4140 }
4141 return InitRequired;
4142}
4143
4144
4145/// Emit task_dup function (for initialization of
4146/// private/firstprivate/lastprivate vars and last_iter flag)
4147/// \code
4148/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4149/// lastpriv) {
4150/// // setup lastprivate flag
4151/// task_dst->last = lastpriv;
4152/// // could be constructor calls here...
4153/// }
4154/// \endcode
4155static llvm::Value *
4156emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4157 const OMPExecutableDirective &D,
4158 QualType KmpTaskTWithPrivatesPtrQTy,
4159 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4160 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4161 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4162 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4163 auto &C = CGM.getContext();
4164 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004165 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4166 KmpTaskTWithPrivatesPtrQTy,
4167 ImplicitParamDecl::Other);
4168 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4169 KmpTaskTWithPrivatesPtrQTy,
4170 ImplicitParamDecl::Other);
4171 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4172 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004173 Args.push_back(&DstArg);
4174 Args.push_back(&SrcArg);
4175 Args.push_back(&LastprivArg);
4176 auto &TaskDupFnInfo =
4177 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4178 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4179 auto *TaskDup =
4180 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4181 ".omp_task_dup.", &CGM.getModule());
4182 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4183 CodeGenFunction CGF(CGM);
4184 CGF.disableDebugInfo();
4185 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4186
4187 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4188 CGF.GetAddrOfLocalVar(&DstArg),
4189 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4190 // task_dst->liter = lastpriv;
4191 if (WithLastIter) {
4192 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4193 LValue Base = CGF.EmitLValueForField(
4194 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4195 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4196 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4197 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4198 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4199 }
4200
4201 // Emit initial values for private copies (if any).
4202 assert(!Privates.empty());
4203 Address KmpTaskSharedsPtr = Address::invalid();
4204 if (!Data.FirstprivateVars.empty()) {
4205 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4206 CGF.GetAddrOfLocalVar(&SrcArg),
4207 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4208 LValue Base = CGF.EmitLValueForField(
4209 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4210 KmpTaskSharedsPtr = Address(
4211 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4212 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4213 KmpTaskTShareds)),
4214 Loc),
4215 CGF.getNaturalTypeAlignment(SharedsTy));
4216 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004217 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4218 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004219 CGF.FinishFunction();
4220 return TaskDup;
4221}
4222
Alexey Bataev8a831592016-05-10 10:36:51 +00004223/// Checks if destructor function is required to be generated.
4224/// \return true if cleanups are required, false otherwise.
4225static bool
4226checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4227 bool NeedsCleanup = false;
4228 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4229 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4230 for (auto *FD : PrivateRD->fields()) {
4231 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4232 if (NeedsCleanup)
4233 break;
4234 }
4235 return NeedsCleanup;
4236}
4237
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004238CGOpenMPRuntime::TaskResultTy
4239CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4240 const OMPExecutableDirective &D,
4241 llvm::Value *TaskFunction, QualType SharedsTy,
4242 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004243 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004244 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004245 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004246 auto I = Data.PrivateCopies.begin();
4247 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004248 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4249 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004250 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004251 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4252 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004253 ++I;
4254 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004255 I = Data.FirstprivateCopies.begin();
4256 auto IElemInitRef = Data.FirstprivateInits.begin();
4257 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004258 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4259 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004260 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004261 PrivateHelpersTy(
4262 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4263 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004264 ++I;
4265 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004266 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004267 I = Data.LastprivateCopies.begin();
4268 for (auto *E : Data.LastprivateVars) {
4269 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4270 Privates.push_back(std::make_pair(
4271 C.getDeclAlign(VD),
4272 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4273 /*PrivateElemInit=*/nullptr)));
4274 ++I;
4275 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004276 llvm::array_pod_sort(Privates.begin(), Privates.end(),
4277 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004278 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4279 // Build type kmp_routine_entry_t (if not built yet).
4280 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004281 // Build type kmp_task_t (if not built yet).
4282 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004283 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4284 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004285 }
4286 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004287 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004288 auto *KmpTaskTWithPrivatesQTyRD =
4289 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4290 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4291 QualType KmpTaskTWithPrivatesPtrQTy =
4292 C.getPointerType(KmpTaskTWithPrivatesQTy);
4293 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4294 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004295 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004296 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4297
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004298 // Emit initial values for private copies (if any).
4299 llvm::Value *TaskPrivatesMap = nullptr;
4300 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004301 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004302 if (!Privates.empty()) {
4303 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004304 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4305 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4306 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004307 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4308 TaskPrivatesMap, TaskPrivatesMapTy);
4309 } else {
4310 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4311 cast<llvm::PointerType>(TaskPrivatesMapTy));
4312 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004313 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4314 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004315 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004316 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4317 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4318 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004319
4320 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4321 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4322 // kmp_routine_entry_t *task_entry);
4323 // Task flags. Format is taken from
4324 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4325 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004326 enum {
4327 TiedFlag = 0x1,
4328 FinalFlag = 0x2,
4329 DestructorsFlag = 0x8,
4330 PriorityFlag = 0x20
4331 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004332 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004333 bool NeedsCleanup = false;
4334 if (!Privates.empty()) {
4335 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4336 if (NeedsCleanup)
4337 Flags = Flags | DestructorsFlag;
4338 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004339 if (Data.Priority.getInt())
4340 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004341 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004342 Data.Final.getPointer()
4343 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004344 CGF.Builder.getInt32(FinalFlag),
4345 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004346 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004347 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004348 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004349 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4350 getThreadID(CGF, Loc), TaskFlags,
4351 KmpTaskTWithPrivatesTySize, SharedsSize,
4352 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4353 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004354 auto *NewTask = CGF.EmitRuntimeCall(
4355 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004356 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4357 NewTask, KmpTaskTWithPrivatesPtrTy);
4358 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4359 KmpTaskTWithPrivatesQTy);
4360 LValue TDBase =
4361 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004362 // Fill the data in the resulting kmp_task_t record.
4363 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004364 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004365 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004366 KmpTaskSharedsPtr =
4367 Address(CGF.EmitLoadOfScalar(
4368 CGF.EmitLValueForField(
4369 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4370 KmpTaskTShareds)),
4371 Loc),
4372 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004373 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004374 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004375 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004376 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004377 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004378 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4379 SharedsTy, SharedsPtrTy, Data, Privates,
4380 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004381 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4382 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4383 Result.TaskDupFn = emitTaskDupFunction(
4384 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4385 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4386 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004387 }
4388 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004389 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4390 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004391 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004392 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4393 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4394 if (NeedsCleanup) {
4395 llvm::Value *DestructorFn = emitDestructorsFunction(
4396 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4397 KmpTaskTWithPrivatesQTy);
4398 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4399 LValue DestructorsLV = CGF.EmitLValueForField(
4400 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4401 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4402 DestructorFn, KmpRoutineEntryPtrTy),
4403 DestructorsLV);
4404 }
4405 // Set priority.
4406 if (Data.Priority.getInt()) {
4407 LValue Data2LV = CGF.EmitLValueForField(
4408 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4409 LValue PriorityLV = CGF.EmitLValueForField(
4410 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4411 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4412 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004413 Result.NewTask = NewTask;
4414 Result.TaskEntry = TaskEntry;
4415 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4416 Result.TDBase = TDBase;
4417 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4418 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004419}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004420
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004421void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4422 const OMPExecutableDirective &D,
4423 llvm::Value *TaskFunction,
4424 QualType SharedsTy, Address Shareds,
4425 const Expr *IfCond,
4426 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004427 if (!CGF.HaveInsertPoint())
4428 return;
4429
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004430 TaskResultTy Result =
4431 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4432 llvm::Value *NewTask = Result.NewTask;
4433 llvm::Value *TaskEntry = Result.TaskEntry;
4434 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4435 LValue TDBase = Result.TDBase;
4436 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004437 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004438 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004439 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004440 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004441 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004442 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004443 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004444 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4445 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004446 QualType FlagsTy =
4447 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004448 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4449 if (KmpDependInfoTy.isNull()) {
4450 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4451 KmpDependInfoRD->startDefinition();
4452 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4453 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4454 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4455 KmpDependInfoRD->completeDefinition();
4456 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004457 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004458 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004459 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004460 // Define type kmp_depend_info[<Dependences.size()>];
4461 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004462 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004463 ArrayType::Normal, /*IndexTypeQuals=*/0);
4464 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004465 DependenciesArray =
4466 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004467 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004468 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004469 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004470 llvm::Value *Size;
4471 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004472 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4473 LValue UpAddrLVal =
4474 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4475 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004476 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004477 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004478 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004479 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4480 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004481 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004482 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004483 auto Base = CGF.MakeAddrLValue(
4484 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004485 KmpDependInfoTy);
4486 // deps[i].base_addr = &<Dependences[i].second>;
4487 auto BaseAddrLVal = CGF.EmitLValueForField(
4488 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004489 CGF.EmitStoreOfScalar(
4490 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4491 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004492 // deps[i].len = sizeof(<Dependences[i].second>);
4493 auto LenLVal = CGF.EmitLValueForField(
4494 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4495 CGF.EmitStoreOfScalar(Size, LenLVal);
4496 // deps[i].flags = <Dependences[i].first>;
4497 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004498 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004499 case OMPC_DEPEND_in:
4500 DepKind = DepIn;
4501 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004502 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004503 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004504 case OMPC_DEPEND_inout:
4505 DepKind = DepInOut;
4506 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004507 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004508 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004509 case OMPC_DEPEND_unknown:
4510 llvm_unreachable("Unknown task dependence type");
4511 }
4512 auto FlagsLVal = CGF.EmitLValueForField(
4513 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4514 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4515 FlagsLVal);
4516 }
John McCall7f416cc2015-09-08 08:05:57 +00004517 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4518 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004519 CGF.VoidPtrTy);
4520 }
4521
Alexey Bataev62b63b12015-03-10 07:28:44 +00004522 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4523 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004524 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4525 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4526 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4527 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004528 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004529 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004530 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4531 llvm::Value *DepTaskArgs[7];
4532 if (NumDependencies) {
4533 DepTaskArgs[0] = UpLoc;
4534 DepTaskArgs[1] = ThreadID;
4535 DepTaskArgs[2] = NewTask;
4536 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4537 DepTaskArgs[4] = DependenciesArray.getPointer();
4538 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4539 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4540 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004541 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4542 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004543 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004544 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004545 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4546 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4547 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4548 }
John McCall7f416cc2015-09-08 08:05:57 +00004549 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004550 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004551 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004552 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004553 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004554 TaskArgs);
4555 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004556 // Check if parent region is untied and build return for untied task;
4557 if (auto *Region =
4558 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4559 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004560 };
John McCall7f416cc2015-09-08 08:05:57 +00004561
4562 llvm::Value *DepWaitTaskArgs[6];
4563 if (NumDependencies) {
4564 DepWaitTaskArgs[0] = UpLoc;
4565 DepWaitTaskArgs[1] = ThreadID;
4566 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4567 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4568 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4569 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4570 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004571 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004572 NumDependencies, &DepWaitTaskArgs,
4573 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004574 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004575 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4576 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4577 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4578 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4579 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004580 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004581 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004582 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004583 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004584 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4585 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004586 Action.Enter(CGF);
4587 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004588 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004589 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004590 };
4591
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004592 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4593 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004594 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4595 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004596 RegionCodeGenTy RCG(CodeGen);
4597 CommonActionTy Action(
4598 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4599 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4600 RCG.setAction(Action);
4601 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004602 };
John McCall7f416cc2015-09-08 08:05:57 +00004603
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004604 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004605 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004606 else {
4607 RegionCodeGenTy ThenRCG(ThenCodeGen);
4608 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004609 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004610}
4611
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004612void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4613 const OMPLoopDirective &D,
4614 llvm::Value *TaskFunction,
4615 QualType SharedsTy, Address Shareds,
4616 const Expr *IfCond,
4617 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004618 if (!CGF.HaveInsertPoint())
4619 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004620 TaskResultTy Result =
4621 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004622 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4623 // libcall.
4624 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4625 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4626 // sched, kmp_uint64 grainsize, void *task_dup);
4627 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4628 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4629 llvm::Value *IfVal;
4630 if (IfCond) {
4631 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4632 /*isSigned=*/true);
4633 } else
4634 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4635
4636 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004637 Result.TDBase,
4638 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004639 auto *LBVar =
4640 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4641 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4642 /*IsInitializer=*/true);
4643 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004644 Result.TDBase,
4645 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004646 auto *UBVar =
4647 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4648 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4649 /*IsInitializer=*/true);
4650 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004651 Result.TDBase,
4652 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004653 auto *StVar =
4654 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4655 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4656 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004657 // Store reductions address.
4658 LValue RedLVal = CGF.EmitLValueForField(
4659 Result.TDBase,
4660 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4661 if (Data.Reductions)
4662 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4663 else {
4664 CGF.EmitNullInitialization(RedLVal.getAddress(),
4665 CGF.getContext().VoidPtrTy);
4666 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004667 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004668 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004669 UpLoc,
4670 ThreadID,
4671 Result.NewTask,
4672 IfVal,
4673 LBLVal.getPointer(),
4674 UBLVal.getPointer(),
4675 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4676 llvm::ConstantInt::getNullValue(
4677 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004678 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004679 CGF.IntTy, Data.Schedule.getPointer()
4680 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004681 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004682 Data.Schedule.getPointer()
4683 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004684 /*isSigned=*/false)
4685 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004686 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4687 Result.TaskDupFn, CGF.VoidPtrTy)
4688 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004689 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4690}
4691
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004692/// \brief Emit reduction operation for each element of array (required for
4693/// array sections) LHS op = RHS.
4694/// \param Type Type of array.
4695/// \param LHSVar Variable on the left side of the reduction operation
4696/// (references element of array in original variable).
4697/// \param RHSVar Variable on the right side of the reduction operation
4698/// (references element of array in original variable).
4699/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4700/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004701static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004702 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4703 const VarDecl *RHSVar,
4704 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4705 const Expr *, const Expr *)> &RedOpGen,
4706 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4707 const Expr *UpExpr = nullptr) {
4708 // Perform element-by-element initialization.
4709 QualType ElementTy;
4710 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4711 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4712
4713 // Drill down to the base element type on both arrays.
4714 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4715 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4716
4717 auto RHSBegin = RHSAddr.getPointer();
4718 auto LHSBegin = LHSAddr.getPointer();
4719 // Cast from pointer to array type to pointer to single element.
4720 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4721 // The basic structure here is a while-do loop.
4722 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4723 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4724 auto IsEmpty =
4725 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4726 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4727
4728 // Enter the loop body, making that address the current address.
4729 auto EntryBB = CGF.Builder.GetInsertBlock();
4730 CGF.EmitBlock(BodyBB);
4731
4732 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4733
4734 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4735 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4736 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4737 Address RHSElementCurrent =
4738 Address(RHSElementPHI,
4739 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4740
4741 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4742 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4743 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4744 Address LHSElementCurrent =
4745 Address(LHSElementPHI,
4746 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4747
4748 // Emit copy.
4749 CodeGenFunction::OMPPrivateScope Scope(CGF);
4750 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4751 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4752 Scope.Privatize();
4753 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4754 Scope.ForceCleanup();
4755
4756 // Shift the address forward by one element.
4757 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4758 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4759 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4760 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4761 // Check whether we've reached the end.
4762 auto Done =
4763 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4764 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4765 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4766 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4767
4768 // Done.
4769 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4770}
4771
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004772/// Emit reduction combiner. If the combiner is a simple expression emit it as
4773/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4774/// UDR combiner function.
4775static void emitReductionCombiner(CodeGenFunction &CGF,
4776 const Expr *ReductionOp) {
4777 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4778 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4779 if (auto *DRE =
4780 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4781 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4782 std::pair<llvm::Function *, llvm::Function *> Reduction =
4783 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4784 RValue Func = RValue::get(Reduction.first);
4785 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4786 CGF.EmitIgnoredExpr(ReductionOp);
4787 return;
4788 }
4789 CGF.EmitIgnoredExpr(ReductionOp);
4790}
4791
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004792llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4793 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4794 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4795 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004796 auto &C = CGM.getContext();
4797
4798 // void reduction_func(void *LHSArg, void *RHSArg);
4799 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004800 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4801 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004802 Args.push_back(&LHSArg);
4803 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004804 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004805 auto *Fn = llvm::Function::Create(
4806 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4807 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004808 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004809 CodeGenFunction CGF(CGM);
4810 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4811
4812 // Dst = (void*[n])(LHSArg);
4813 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004814 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4815 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4816 ArgsType), CGF.getPointerAlign());
4817 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4818 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4819 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004820
4821 // ...
4822 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4823 // ...
4824 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004825 auto IPriv = Privates.begin();
4826 unsigned Idx = 0;
4827 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004828 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4829 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004830 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004831 });
4832 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4833 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004834 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004835 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004836 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004837 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004838 // Get array size and emit VLA type.
4839 ++Idx;
4840 Address Elem =
4841 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4842 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004843 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4844 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004845 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004846 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004847 CGF.EmitVariablyModifiedType(PrivTy);
4848 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004849 }
4850 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004851 IPriv = Privates.begin();
4852 auto ILHS = LHSExprs.begin();
4853 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004854 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004855 if ((*IPriv)->getType()->isArrayType()) {
4856 // Emit reduction for array section.
4857 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4858 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004859 EmitOMPAggregateReduction(
4860 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4861 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4862 emitReductionCombiner(CGF, E);
4863 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004864 } else
4865 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004866 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004867 ++IPriv;
4868 ++ILHS;
4869 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004870 }
4871 Scope.ForceCleanup();
4872 CGF.FinishFunction();
4873 return Fn;
4874}
4875
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004876void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4877 const Expr *ReductionOp,
4878 const Expr *PrivateRef,
4879 const DeclRefExpr *LHS,
4880 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004881 if (PrivateRef->getType()->isArrayType()) {
4882 // Emit reduction for array section.
4883 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4884 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4885 EmitOMPAggregateReduction(
4886 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4887 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4888 emitReductionCombiner(CGF, ReductionOp);
4889 });
4890 } else
4891 // Emit reduction for array subscript or single variable.
4892 emitReductionCombiner(CGF, ReductionOp);
4893}
4894
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004895void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004896 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004897 ArrayRef<const Expr *> LHSExprs,
4898 ArrayRef<const Expr *> RHSExprs,
4899 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004900 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004901 if (!CGF.HaveInsertPoint())
4902 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004903
4904 bool WithNowait = Options.WithNowait;
4905 bool SimpleReduction = Options.SimpleReduction;
4906
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004907 // Next code should be emitted for reduction:
4908 //
4909 // static kmp_critical_name lock = { 0 };
4910 //
4911 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4912 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4913 // ...
4914 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4915 // *(Type<n>-1*)rhs[<n>-1]);
4916 // }
4917 //
4918 // ...
4919 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4920 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4921 // RedList, reduce_func, &<lock>)) {
4922 // case 1:
4923 // ...
4924 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4925 // ...
4926 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4927 // break;
4928 // case 2:
4929 // ...
4930 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4931 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004932 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004933 // break;
4934 // default:;
4935 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004936 //
4937 // if SimpleReduction is true, only the next code is generated:
4938 // ...
4939 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4940 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004941
4942 auto &C = CGM.getContext();
4943
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004944 if (SimpleReduction) {
4945 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004946 auto IPriv = Privates.begin();
4947 auto ILHS = LHSExprs.begin();
4948 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004949 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004950 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4951 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004952 ++IPriv;
4953 ++ILHS;
4954 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004955 }
4956 return;
4957 }
4958
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004959 // 1. Build a list of reduction variables.
4960 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004961 auto Size = RHSExprs.size();
4962 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004963 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004964 // Reserve place for array size.
4965 ++Size;
4966 }
4967 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004968 QualType ReductionArrayTy =
4969 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4970 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004971 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004972 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004973 auto IPriv = Privates.begin();
4974 unsigned Idx = 0;
4975 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004976 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004977 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004978 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004979 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004980 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4981 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004982 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004983 // Store array size.
4984 ++Idx;
4985 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4986 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004987 llvm::Value *Size = CGF.Builder.CreateIntCast(
4988 CGF.getVLASize(
4989 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4990 .first,
4991 CGF.SizeTy, /*isSigned=*/false);
4992 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4993 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004994 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004995 }
4996
4997 // 2. Emit reduce_func().
4998 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004999 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
5000 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005001
5002 // 3. Create static kmp_critical_name lock = { 0 };
5003 auto *Lock = getCriticalRegionLock(".reduction");
5004
5005 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5006 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005007 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005008 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005009 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005010 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5011 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005012 llvm::Value *Args[] = {
5013 IdentTLoc, // ident_t *<loc>
5014 ThreadId, // i32 <gtid>
5015 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5016 ReductionArrayTySize, // size_type sizeof(RedList)
5017 RL, // void *RedList
5018 ReductionFn, // void (*) (void *, void *) <reduce_func>
5019 Lock // kmp_critical_name *&<lock>
5020 };
5021 auto Res = CGF.EmitRuntimeCall(
5022 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5023 : OMPRTL__kmpc_reduce),
5024 Args);
5025
5026 // 5. Build switch(res)
5027 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5028 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5029
5030 // 6. Build case 1:
5031 // ...
5032 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5033 // ...
5034 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5035 // break;
5036 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5037 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5038 CGF.EmitBlock(Case1BB);
5039
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005040 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5041 llvm::Value *EndArgs[] = {
5042 IdentTLoc, // ident_t *<loc>
5043 ThreadId, // i32 <gtid>
5044 Lock // kmp_critical_name *&<lock>
5045 };
5046 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5047 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005048 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005049 auto IPriv = Privates.begin();
5050 auto ILHS = LHSExprs.begin();
5051 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005052 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005053 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5054 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005055 ++IPriv;
5056 ++ILHS;
5057 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005058 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005059 };
5060 RegionCodeGenTy RCG(CodeGen);
5061 CommonActionTy Action(
5062 nullptr, llvm::None,
5063 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5064 : OMPRTL__kmpc_end_reduce),
5065 EndArgs);
5066 RCG.setAction(Action);
5067 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005068
5069 CGF.EmitBranch(DefaultBB);
5070
5071 // 7. Build case 2:
5072 // ...
5073 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5074 // ...
5075 // break;
5076 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5077 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5078 CGF.EmitBlock(Case2BB);
5079
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005080 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5081 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005082 auto ILHS = LHSExprs.begin();
5083 auto IRHS = RHSExprs.begin();
5084 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005085 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005086 const Expr *XExpr = nullptr;
5087 const Expr *EExpr = nullptr;
5088 const Expr *UpExpr = nullptr;
5089 BinaryOperatorKind BO = BO_Comma;
5090 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5091 if (BO->getOpcode() == BO_Assign) {
5092 XExpr = BO->getLHS();
5093 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005094 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005095 }
5096 // Try to emit update expression as a simple atomic.
5097 auto *RHSExpr = UpExpr;
5098 if (RHSExpr) {
5099 // Analyze RHS part of the whole expression.
5100 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5101 RHSExpr->IgnoreParenImpCasts())) {
5102 // If this is a conditional operator, analyze its condition for
5103 // min/max reduction operator.
5104 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005105 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005106 if (auto *BORHS =
5107 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5108 EExpr = BORHS->getRHS();
5109 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005110 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005111 }
5112 if (XExpr) {
5113 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005114 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005115 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5116 const Expr *EExpr, const Expr *UpExpr) {
5117 LValue X = CGF.EmitLValue(XExpr);
5118 RValue E;
5119 if (EExpr)
5120 E = CGF.EmitAnyExpr(EExpr);
5121 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005122 X, E, BO, /*IsXLHSInRHSPart=*/true,
5123 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005124 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005125 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5126 PrivateScope.addPrivate(
5127 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5128 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5129 CGF.emitOMPSimpleStore(
5130 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5131 VD->getType().getNonReferenceType(), Loc);
5132 return LHSTemp;
5133 });
5134 (void)PrivateScope.Privatize();
5135 return CGF.EmitAnyExpr(UpExpr);
5136 });
5137 };
5138 if ((*IPriv)->getType()->isArrayType()) {
5139 // Emit atomic reduction for array section.
5140 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5141 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5142 AtomicRedGen, XExpr, EExpr, UpExpr);
5143 } else
5144 // Emit atomic reduction for array subscript or single variable.
5145 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5146 } else {
5147 // Emit as a critical region.
5148 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5149 const Expr *, const Expr *) {
5150 auto &RT = CGF.CGM.getOpenMPRuntime();
5151 RT.emitCriticalRegion(
5152 CGF, ".atomic_reduction",
5153 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5154 Action.Enter(CGF);
5155 emitReductionCombiner(CGF, E);
5156 },
5157 Loc);
5158 };
5159 if ((*IPriv)->getType()->isArrayType()) {
5160 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5161 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5162 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5163 CritRedGen);
5164 } else
5165 CritRedGen(CGF, nullptr, nullptr, nullptr);
5166 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005167 ++ILHS;
5168 ++IRHS;
5169 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005170 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005171 };
5172 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5173 if (!WithNowait) {
5174 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5175 llvm::Value *EndArgs[] = {
5176 IdentTLoc, // ident_t *<loc>
5177 ThreadId, // i32 <gtid>
5178 Lock // kmp_critical_name *&<lock>
5179 };
5180 CommonActionTy Action(nullptr, llvm::None,
5181 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5182 EndArgs);
5183 AtomicRCG.setAction(Action);
5184 AtomicRCG(CGF);
5185 } else
5186 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005187
5188 CGF.EmitBranch(DefaultBB);
5189 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5190}
5191
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005192/// Generates unique name for artificial threadprivate variables.
5193/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5194static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5195 unsigned N) {
5196 SmallString<256> Buffer;
5197 llvm::raw_svector_ostream Out(Buffer);
5198 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5199 return Out.str();
5200}
5201
5202/// Emits reduction initializer function:
5203/// \code
5204/// void @.red_init(void* %arg) {
5205/// %0 = bitcast void* %arg to <type>*
5206/// store <type> <init>, <type>* %0
5207/// ret void
5208/// }
5209/// \endcode
5210static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5211 SourceLocation Loc,
5212 ReductionCodeGen &RCG, unsigned N) {
5213 auto &C = CGM.getContext();
5214 FunctionArgList Args;
5215 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5216 Args.emplace_back(&Param);
5217 auto &FnInfo =
5218 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5219 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5220 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5221 ".red_init.", &CGM.getModule());
5222 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5223 CodeGenFunction CGF(CGM);
5224 CGF.disableDebugInfo();
5225 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5226 Address PrivateAddr = CGF.EmitLoadOfPointer(
5227 CGF.GetAddrOfLocalVar(&Param),
5228 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5229 llvm::Value *Size = nullptr;
5230 // If the size of the reduction item is non-constant, load it from global
5231 // threadprivate variable.
5232 if (RCG.getSizes(N).second) {
5233 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5234 CGF, CGM.getContext().getSizeType(),
5235 generateUniqueName("reduction_size", Loc, N));
5236 Size =
5237 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5238 CGM.getContext().getSizeType(), SourceLocation());
5239 }
5240 RCG.emitAggregateType(CGF, N, Size);
5241 LValue SharedLVal;
5242 // If initializer uses initializer from declare reduction construct, emit a
5243 // pointer to the address of the original reduction item (reuired by reduction
5244 // initializer)
5245 if (RCG.usesReductionInitializer(N)) {
5246 Address SharedAddr =
5247 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5248 CGF, CGM.getContext().VoidPtrTy,
5249 generateUniqueName("reduction", Loc, N));
5250 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5251 } else {
5252 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5253 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5254 CGM.getContext().VoidPtrTy);
5255 }
5256 // Emit the initializer:
5257 // %0 = bitcast void* %arg to <type>*
5258 // store <type> <init>, <type>* %0
5259 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5260 [](CodeGenFunction &) { return false; });
5261 CGF.FinishFunction();
5262 return Fn;
5263}
5264
5265/// Emits reduction combiner function:
5266/// \code
5267/// void @.red_comb(void* %arg0, void* %arg1) {
5268/// %lhs = bitcast void* %arg0 to <type>*
5269/// %rhs = bitcast void* %arg1 to <type>*
5270/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5271/// store <type> %2, <type>* %lhs
5272/// ret void
5273/// }
5274/// \endcode
5275static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5276 SourceLocation Loc,
5277 ReductionCodeGen &RCG, unsigned N,
5278 const Expr *ReductionOp,
5279 const Expr *LHS, const Expr *RHS,
5280 const Expr *PrivateRef) {
5281 auto &C = CGM.getContext();
5282 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5283 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5284 FunctionArgList Args;
5285 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5286 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5287 Args.emplace_back(&ParamInOut);
5288 Args.emplace_back(&ParamIn);
5289 auto &FnInfo =
5290 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5291 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5292 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5293 ".red_comb.", &CGM.getModule());
5294 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5295 CodeGenFunction CGF(CGM);
5296 CGF.disableDebugInfo();
5297 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5298 llvm::Value *Size = nullptr;
5299 // If the size of the reduction item is non-constant, load it from global
5300 // threadprivate variable.
5301 if (RCG.getSizes(N).second) {
5302 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5303 CGF, CGM.getContext().getSizeType(),
5304 generateUniqueName("reduction_size", Loc, N));
5305 Size =
5306 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5307 CGM.getContext().getSizeType(), SourceLocation());
5308 }
5309 RCG.emitAggregateType(CGF, N, Size);
5310 // Remap lhs and rhs variables to the addresses of the function arguments.
5311 // %lhs = bitcast void* %arg0 to <type>*
5312 // %rhs = bitcast void* %arg1 to <type>*
5313 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5314 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5315 // Pull out the pointer to the variable.
5316 Address PtrAddr = CGF.EmitLoadOfPointer(
5317 CGF.GetAddrOfLocalVar(&ParamInOut),
5318 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5319 return CGF.Builder.CreateElementBitCast(
5320 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5321 });
5322 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5323 // Pull out the pointer to the variable.
5324 Address PtrAddr = CGF.EmitLoadOfPointer(
5325 CGF.GetAddrOfLocalVar(&ParamIn),
5326 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5327 return CGF.Builder.CreateElementBitCast(
5328 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5329 });
5330 PrivateScope.Privatize();
5331 // Emit the combiner body:
5332 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5333 // store <type> %2, <type>* %lhs
5334 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5335 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5336 cast<DeclRefExpr>(RHS));
5337 CGF.FinishFunction();
5338 return Fn;
5339}
5340
5341/// Emits reduction finalizer function:
5342/// \code
5343/// void @.red_fini(void* %arg) {
5344/// %0 = bitcast void* %arg to <type>*
5345/// <destroy>(<type>* %0)
5346/// ret void
5347/// }
5348/// \endcode
5349static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5350 SourceLocation Loc,
5351 ReductionCodeGen &RCG, unsigned N) {
5352 if (!RCG.needCleanups(N))
5353 return nullptr;
5354 auto &C = CGM.getContext();
5355 FunctionArgList Args;
5356 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5357 Args.emplace_back(&Param);
5358 auto &FnInfo =
5359 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5360 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5361 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5362 ".red_fini.", &CGM.getModule());
5363 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5364 CodeGenFunction CGF(CGM);
5365 CGF.disableDebugInfo();
5366 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5367 Address PrivateAddr = CGF.EmitLoadOfPointer(
5368 CGF.GetAddrOfLocalVar(&Param),
5369 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5370 llvm::Value *Size = nullptr;
5371 // If the size of the reduction item is non-constant, load it from global
5372 // threadprivate variable.
5373 if (RCG.getSizes(N).second) {
5374 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5375 CGF, CGM.getContext().getSizeType(),
5376 generateUniqueName("reduction_size", Loc, N));
5377 Size =
5378 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5379 CGM.getContext().getSizeType(), SourceLocation());
5380 }
5381 RCG.emitAggregateType(CGF, N, Size);
5382 // Emit the finalizer body:
5383 // <destroy>(<type>* %0)
5384 RCG.emitCleanups(CGF, N, PrivateAddr);
5385 CGF.FinishFunction();
5386 return Fn;
5387}
5388
5389llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5390 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5391 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5392 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5393 return nullptr;
5394
5395 // Build typedef struct:
5396 // kmp_task_red_input {
5397 // void *reduce_shar; // shared reduction item
5398 // size_t reduce_size; // size of data item
5399 // void *reduce_init; // data initialization routine
5400 // void *reduce_fini; // data finalization routine
5401 // void *reduce_comb; // data combiner routine
5402 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5403 // } kmp_task_red_input_t;
5404 ASTContext &C = CGM.getContext();
5405 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5406 RD->startDefinition();
5407 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5408 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5409 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5410 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5411 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5412 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5413 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5414 RD->completeDefinition();
5415 QualType RDType = C.getRecordType(RD);
5416 unsigned Size = Data.ReductionVars.size();
5417 llvm::APInt ArraySize(/*numBits=*/64, Size);
5418 QualType ArrayRDType = C.getConstantArrayType(
5419 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5420 // kmp_task_red_input_t .rd_input.[Size];
5421 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5422 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5423 Data.ReductionOps);
5424 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5425 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5426 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5427 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5428 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5429 TaskRedInput.getPointer(), Idxs,
5430 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5431 ".rd_input.gep.");
5432 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5433 // ElemLVal.reduce_shar = &Shareds[Cnt];
5434 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5435 RCG.emitSharedLValue(CGF, Cnt);
5436 llvm::Value *CastedShared =
5437 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5438 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5439 RCG.emitAggregateType(CGF, Cnt);
5440 llvm::Value *SizeValInChars;
5441 llvm::Value *SizeVal;
5442 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5443 // We use delayed creation/initialization for VLAs, array sections and
5444 // custom reduction initializations. It is required because runtime does not
5445 // provide the way to pass the sizes of VLAs/array sections to
5446 // initializer/combiner/finalizer functions and does not pass the pointer to
5447 // original reduction item to the initializer. Instead threadprivate global
5448 // variables are used to store these values and use them in the functions.
5449 bool DelayedCreation = !!SizeVal;
5450 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5451 /*isSigned=*/false);
5452 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5453 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5454 // ElemLVal.reduce_init = init;
5455 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5456 llvm::Value *InitAddr =
5457 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5458 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5459 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5460 // ElemLVal.reduce_fini = fini;
5461 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5462 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5463 llvm::Value *FiniAddr = Fini
5464 ? CGF.EmitCastToVoidPtr(Fini)
5465 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5466 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5467 // ElemLVal.reduce_comb = comb;
5468 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5469 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5470 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5471 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5472 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5473 // ElemLVal.flags = 0;
5474 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5475 if (DelayedCreation) {
5476 CGF.EmitStoreOfScalar(
5477 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5478 FlagsLVal);
5479 } else
5480 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5481 }
5482 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5483 // *data);
5484 llvm::Value *Args[] = {
5485 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5486 /*isSigned=*/true),
5487 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5488 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5489 CGM.VoidPtrTy)};
5490 return CGF.EmitRuntimeCall(
5491 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5492}
5493
5494void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5495 SourceLocation Loc,
5496 ReductionCodeGen &RCG,
5497 unsigned N) {
5498 auto Sizes = RCG.getSizes(N);
5499 // Emit threadprivate global variable if the type is non-constant
5500 // (Sizes.second = nullptr).
5501 if (Sizes.second) {
5502 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5503 /*isSigned=*/false);
5504 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5505 CGF, CGM.getContext().getSizeType(),
5506 generateUniqueName("reduction_size", Loc, N));
5507 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5508 }
5509 // Store address of the original reduction item if custom initializer is used.
5510 if (RCG.usesReductionInitializer(N)) {
5511 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5512 CGF, CGM.getContext().VoidPtrTy,
5513 generateUniqueName("reduction", Loc, N));
5514 CGF.Builder.CreateStore(
5515 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5516 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5517 SharedAddr, /*IsVolatile=*/false);
5518 }
5519}
5520
5521Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5522 SourceLocation Loc,
5523 llvm::Value *ReductionsPtr,
5524 LValue SharedLVal) {
5525 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5526 // *d);
5527 llvm::Value *Args[] = {
5528 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5529 /*isSigned=*/true),
5530 ReductionsPtr,
5531 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5532 CGM.VoidPtrTy)};
5533 return Address(
5534 CGF.EmitRuntimeCall(
5535 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5536 SharedLVal.getAlignment());
5537}
5538
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005539void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5540 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005541 if (!CGF.HaveInsertPoint())
5542 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005543 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5544 // global_tid);
5545 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5546 // Ignore return result until untied tasks are supported.
5547 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005548 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5549 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005550}
5551
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005552void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005553 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005554 const RegionCodeGenTy &CodeGen,
5555 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005556 if (!CGF.HaveInsertPoint())
5557 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005558 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005559 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005560}
5561
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005562namespace {
5563enum RTCancelKind {
5564 CancelNoreq = 0,
5565 CancelParallel = 1,
5566 CancelLoop = 2,
5567 CancelSections = 3,
5568 CancelTaskgroup = 4
5569};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005570} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005571
5572static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5573 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005574 if (CancelRegion == OMPD_parallel)
5575 CancelKind = CancelParallel;
5576 else if (CancelRegion == OMPD_for)
5577 CancelKind = CancelLoop;
5578 else if (CancelRegion == OMPD_sections)
5579 CancelKind = CancelSections;
5580 else {
5581 assert(CancelRegion == OMPD_taskgroup);
5582 CancelKind = CancelTaskgroup;
5583 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005584 return CancelKind;
5585}
5586
5587void CGOpenMPRuntime::emitCancellationPointCall(
5588 CodeGenFunction &CGF, SourceLocation Loc,
5589 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005590 if (!CGF.HaveInsertPoint())
5591 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005592 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5593 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005594 if (auto *OMPRegionInfo =
5595 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005596 // For 'cancellation point taskgroup', the task region info may not have a
5597 // cancel. This may instead happen in another adjacent task.
5598 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005599 llvm::Value *Args[] = {
5600 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5601 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005602 // Ignore return result until untied tasks are supported.
5603 auto *Result = CGF.EmitRuntimeCall(
5604 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5605 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005606 // exit from construct;
5607 // }
5608 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5609 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5610 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5611 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5612 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005613 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005614 auto CancelDest =
5615 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005616 CGF.EmitBranchThroughCleanup(CancelDest);
5617 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5618 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005619 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005620}
5621
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005622void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005623 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005624 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005625 if (!CGF.HaveInsertPoint())
5626 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005627 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5628 // kmp_int32 cncl_kind);
5629 if (auto *OMPRegionInfo =
5630 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005631 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5632 PrePostActionTy &) {
5633 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005634 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005635 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005636 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5637 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005638 auto *Result = CGF.EmitRuntimeCall(
5639 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005640 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005641 // exit from construct;
5642 // }
5643 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5644 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5645 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5646 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5647 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005648 // exit from construct;
5649 auto CancelDest =
5650 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5651 CGF.EmitBranchThroughCleanup(CancelDest);
5652 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5653 };
5654 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005655 emitOMPIfClause(CGF, IfCond, ThenGen,
5656 [](CodeGenFunction &, PrePostActionTy &) {});
5657 else {
5658 RegionCodeGenTy ThenRCG(ThenGen);
5659 ThenRCG(CGF);
5660 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005661 }
5662}
Samuel Antaobed3c462015-10-02 16:14:20 +00005663
Samuel Antaoee8fb302016-01-06 13:42:12 +00005664/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005665/// consists of the file and device IDs as well as line number associated with
5666/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005667static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5668 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005669 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005670
5671 auto &SM = C.getSourceManager();
5672
5673 // The loc should be always valid and have a file ID (the user cannot use
5674 // #pragma directives in macros)
5675
5676 assert(Loc.isValid() && "Source location is expected to be always valid.");
5677 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5678
5679 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5680 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5681
5682 llvm::sys::fs::UniqueID ID;
5683 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5684 llvm_unreachable("Source file with target region no longer exists!");
5685
5686 DeviceID = ID.getDevice();
5687 FileID = ID.getFile();
5688 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005689}
5690
5691void CGOpenMPRuntime::emitTargetOutlinedFunction(
5692 const OMPExecutableDirective &D, StringRef ParentName,
5693 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005694 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005695 assert(!ParentName.empty() && "Invalid target region parent name!");
5696
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005697 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5698 IsOffloadEntry, CodeGen);
5699}
5700
5701void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5702 const OMPExecutableDirective &D, StringRef ParentName,
5703 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5704 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005705 // Create a unique name for the entry function using the source location
5706 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005707 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005708 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005709 //
5710 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005711 // mangled name of the function that encloses the target region and BB is the
5712 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005713
5714 unsigned DeviceID;
5715 unsigned FileID;
5716 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005717 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005718 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005719 SmallString<64> EntryFnName;
5720 {
5721 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005722 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5723 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005724 }
5725
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005726 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5727
Samuel Antaobed3c462015-10-02 16:14:20 +00005728 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005729 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005730 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005731
Samuel Antao6d004262016-06-16 18:39:34 +00005732 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005733
5734 // If this target outline function is not an offload entry, we don't need to
5735 // register it.
5736 if (!IsOffloadEntry)
5737 return;
5738
5739 // The target region ID is used by the runtime library to identify the current
5740 // target region, so it only has to be unique and not necessarily point to
5741 // anything. It could be the pointer to the outlined function that implements
5742 // the target region, but we aren't using that so that the compiler doesn't
5743 // need to keep that, and could therefore inline the host function if proven
5744 // worthwhile during optimization. In the other hand, if emitting code for the
5745 // device, the ID has to be the function address so that it can retrieved from
5746 // the offloading entry and launched by the runtime library. We also mark the
5747 // outlined function to have external linkage in case we are emitting code for
5748 // the device, because these functions will be entry points to the device.
5749
5750 if (CGM.getLangOpts().OpenMPIsDevice) {
5751 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5752 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5753 } else
5754 OutlinedFnID = new llvm::GlobalVariable(
5755 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5756 llvm::GlobalValue::PrivateLinkage,
5757 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5758
5759 // Register the information for the entry associated with this target region.
5760 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005761 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5762 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005763}
5764
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005765/// discard all CompoundStmts intervening between two constructs
5766static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5767 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5768 Body = CS->body_front();
5769
5770 return Body;
5771}
5772
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005773/// Emit the number of teams for a target directive. Inspect the num_teams
5774/// clause associated with a teams construct combined or closely nested
5775/// with the target directive.
5776///
5777/// Emit a team of size one for directives such as 'target parallel' that
5778/// have no associated teams construct.
5779///
5780/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005781static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005782emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5783 CodeGenFunction &CGF,
5784 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005785
5786 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5787 "teams directive expected to be "
5788 "emitted only for the host!");
5789
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005790 auto &Bld = CGF.Builder;
5791
5792 // If the target directive is combined with a teams directive:
5793 // Return the value in the num_teams clause, if any.
5794 // Otherwise, return 0 to denote the runtime default.
5795 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5796 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5797 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5798 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5799 /*IgnoreResultAssign*/ true);
5800 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5801 /*IsSigned=*/true);
5802 }
5803
5804 // The default value is 0.
5805 return Bld.getInt32(0);
5806 }
5807
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005808 // If the target directive is combined with a parallel directive but not a
5809 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005810 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5811 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005812
5813 // If the current target region has a teams region enclosed, we need to get
5814 // the number of teams to pass to the runtime function call. This is done
5815 // by generating the expression in a inlined region. This is required because
5816 // the expression is captured in the enclosing target environment when the
5817 // teams directive is not combined with target.
5818
5819 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5820
5821 // FIXME: Accommodate other combined directives with teams when they become
5822 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005823 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5824 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005825 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5826 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5827 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5828 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005829 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5830 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005831 }
5832
5833 // If we have an enclosed teams directive but no num_teams clause we use
5834 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005835 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005836 }
5837
5838 // No teams associated with the directive.
5839 return nullptr;
5840}
5841
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005842/// Emit the number of threads for a target directive. Inspect the
5843/// thread_limit clause associated with a teams construct combined or closely
5844/// nested with the target directive.
5845///
5846/// Emit the num_threads clause for directives such as 'target parallel' that
5847/// have no associated teams construct.
5848///
5849/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005850static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005851emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5852 CodeGenFunction &CGF,
5853 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005854
5855 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5856 "teams directive expected to be "
5857 "emitted only for the host!");
5858
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005859 auto &Bld = CGF.Builder;
5860
5861 //
5862 // If the target directive is combined with a teams directive:
5863 // Return the value in the thread_limit clause, if any.
5864 //
5865 // If the target directive is combined with a parallel directive:
5866 // Return the value in the num_threads clause, if any.
5867 //
5868 // If both clauses are set, select the minimum of the two.
5869 //
5870 // If neither teams or parallel combined directives set the number of threads
5871 // in a team, return 0 to denote the runtime default.
5872 //
5873 // If this is not a teams directive return nullptr.
5874
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005875 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5876 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005877 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5878 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005879 llvm::Value *ThreadLimitVal = nullptr;
5880
5881 if (const auto *ThreadLimitClause =
5882 D.getSingleClause<OMPThreadLimitClause>()) {
5883 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5884 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5885 /*IgnoreResultAssign*/ true);
5886 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5887 /*IsSigned=*/true);
5888 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005889
5890 if (const auto *NumThreadsClause =
5891 D.getSingleClause<OMPNumThreadsClause>()) {
5892 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5893 llvm::Value *NumThreads =
5894 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5895 /*IgnoreResultAssign*/ true);
5896 NumThreadsVal =
5897 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5898 }
5899
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005900 // Select the lesser of thread_limit and num_threads.
5901 if (NumThreadsVal)
5902 ThreadLimitVal = ThreadLimitVal
5903 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5904 ThreadLimitVal),
5905 NumThreadsVal, ThreadLimitVal)
5906 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005907
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005908 // Set default value passed to the runtime if either teams or a target
5909 // parallel type directive is found but no clause is specified.
5910 if (!ThreadLimitVal)
5911 ThreadLimitVal = DefaultThreadLimitVal;
5912
5913 return ThreadLimitVal;
5914 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005915
Samuel Antaob68e2db2016-03-03 16:20:23 +00005916 // If the current target region has a teams region enclosed, we need to get
5917 // the thread limit to pass to the runtime function call. This is done
5918 // by generating the expression in a inlined region. This is required because
5919 // the expression is captured in the enclosing target environment when the
5920 // teams directive is not combined with target.
5921
5922 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5923
5924 // FIXME: Accommodate other combined directives with teams when they become
5925 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005926 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5927 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005928 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5929 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5930 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5931 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5932 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5933 /*IsSigned=*/true);
5934 }
5935
5936 // If we have an enclosed teams directive but no thread_limit clause we use
5937 // the default value 0.
5938 return CGF.Builder.getInt32(0);
5939 }
5940
5941 // No teams associated with the directive.
5942 return nullptr;
5943}
5944
Samuel Antao86ace552016-04-27 22:40:57 +00005945namespace {
5946// \brief Utility to handle information from clauses associated with a given
5947// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5948// It provides a convenient interface to obtain the information and generate
5949// code for that information.
5950class MappableExprsHandler {
5951public:
5952 /// \brief Values for bit flags used to specify the mapping type for
5953 /// offloading.
5954 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005955 /// \brief Allocate memory on the device and move data from host to device.
5956 OMP_MAP_TO = 0x01,
5957 /// \brief Allocate memory on the device and move data from device to host.
5958 OMP_MAP_FROM = 0x02,
5959 /// \brief Always perform the requested mapping action on the element, even
5960 /// if it was already mapped before.
5961 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005962 /// \brief Delete the element from the device environment, ignoring the
5963 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005964 OMP_MAP_DELETE = 0x08,
5965 /// \brief The element being mapped is a pointer, therefore the pointee
5966 /// should be mapped as well.
5967 OMP_MAP_IS_PTR = 0x10,
5968 /// \brief This flags signals that an argument is the first one relating to
5969 /// a map/private clause expression. For some cases a single
5970 /// map/privatization results in multiple arguments passed to the runtime
5971 /// library.
5972 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005973 /// \brief Signal that the runtime library has to return the device pointer
5974 /// in the current position for the data being mapped.
5975 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005976 /// \brief This flag signals that the reference being passed is a pointer to
5977 /// private data.
5978 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005979 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005980 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005981 };
5982
Samuel Antaocc10b852016-07-28 14:23:26 +00005983 /// Class that associates information with a base pointer to be passed to the
5984 /// runtime library.
5985 class BasePointerInfo {
5986 /// The base pointer.
5987 llvm::Value *Ptr = nullptr;
5988 /// The base declaration that refers to this device pointer, or null if
5989 /// there is none.
5990 const ValueDecl *DevPtrDecl = nullptr;
5991
5992 public:
5993 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5994 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5995 llvm::Value *operator*() const { return Ptr; }
5996 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5997 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5998 };
5999
6000 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006001 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
6002 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
6003
6004private:
6005 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006006 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006007
6008 /// \brief Function the directive is being generated for.
6009 CodeGenFunction &CGF;
6010
Samuel Antaod486f842016-05-26 16:53:38 +00006011 /// \brief Set of all first private variables in the current directive.
6012 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6013
Samuel Antao6890b092016-07-28 14:25:09 +00006014 /// Map between device pointer declarations and their expression components.
6015 /// The key value for declarations in 'this' is null.
6016 llvm::DenseMap<
6017 const ValueDecl *,
6018 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6019 DevPointersMap;
6020
Samuel Antao86ace552016-04-27 22:40:57 +00006021 llvm::Value *getExprTypeSize(const Expr *E) const {
6022 auto ExprTy = E->getType().getCanonicalType();
6023
6024 // Reference types are ignored for mapping purposes.
6025 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6026 ExprTy = RefTy->getPointeeType().getCanonicalType();
6027
6028 // Given that an array section is considered a built-in type, we need to
6029 // do the calculation based on the length of the section instead of relying
6030 // on CGF.getTypeSize(E->getType()).
6031 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6032 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6033 OAE->getBase()->IgnoreParenImpCasts())
6034 .getCanonicalType();
6035
6036 // If there is no length associated with the expression, that means we
6037 // are using the whole length of the base.
6038 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6039 return CGF.getTypeSize(BaseTy);
6040
6041 llvm::Value *ElemSize;
6042 if (auto *PTy = BaseTy->getAs<PointerType>())
6043 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6044 else {
6045 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6046 assert(ATy && "Expecting array type if not a pointer type.");
6047 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6048 }
6049
6050 // If we don't have a length at this point, that is because we have an
6051 // array section with a single element.
6052 if (!OAE->getLength())
6053 return ElemSize;
6054
6055 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6056 LengthVal =
6057 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6058 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6059 }
6060 return CGF.getTypeSize(ExprTy);
6061 }
6062
6063 /// \brief Return the corresponding bits for a given map clause modifier. Add
6064 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006065 /// map as the first one of a series of maps that relate to the same map
6066 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00006067 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6068 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00006069 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006070 unsigned Bits = 0u;
6071 switch (MapType) {
6072 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006073 case OMPC_MAP_release:
6074 // alloc and release is the default behavior in the runtime library, i.e.
6075 // if we don't pass any bits alloc/release that is what the runtime is
6076 // going to do. Therefore, we don't need to signal anything for these two
6077 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006078 break;
6079 case OMPC_MAP_to:
6080 Bits = OMP_MAP_TO;
6081 break;
6082 case OMPC_MAP_from:
6083 Bits = OMP_MAP_FROM;
6084 break;
6085 case OMPC_MAP_tofrom:
6086 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6087 break;
6088 case OMPC_MAP_delete:
6089 Bits = OMP_MAP_DELETE;
6090 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006091 default:
6092 llvm_unreachable("Unexpected map type!");
6093 break;
6094 }
6095 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00006096 Bits |= OMP_MAP_IS_PTR;
6097 if (AddIsFirstFlag)
6098 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00006099 if (MapTypeModifier == OMPC_MAP_always)
6100 Bits |= OMP_MAP_ALWAYS;
6101 return Bits;
6102 }
6103
6104 /// \brief Return true if the provided expression is a final array section. A
6105 /// final array section, is one whose length can't be proved to be one.
6106 bool isFinalArraySectionExpression(const Expr *E) const {
6107 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6108
6109 // It is not an array section and therefore not a unity-size one.
6110 if (!OASE)
6111 return false;
6112
6113 // An array section with no colon always refer to a single element.
6114 if (OASE->getColonLoc().isInvalid())
6115 return false;
6116
6117 auto *Length = OASE->getLength();
6118
6119 // If we don't have a length we have to check if the array has size 1
6120 // for this dimension. Also, we should always expect a length if the
6121 // base type is pointer.
6122 if (!Length) {
6123 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6124 OASE->getBase()->IgnoreParenImpCasts())
6125 .getCanonicalType();
6126 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6127 return ATy->getSize().getSExtValue() != 1;
6128 // If we don't have a constant dimension length, we have to consider
6129 // the current section as having any size, so it is not necessarily
6130 // unitary. If it happen to be unity size, that's user fault.
6131 return true;
6132 }
6133
6134 // Check if the length evaluates to 1.
6135 llvm::APSInt ConstLength;
6136 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6137 return true; // Can have more that size 1.
6138
6139 return ConstLength.getSExtValue() != 1;
6140 }
6141
6142 /// \brief Generate the base pointers, section pointers, sizes and map type
6143 /// bits for the provided map type, map modifier, and expression components.
6144 /// \a IsFirstComponent should be set to true if the provided set of
6145 /// components is the first associated with a capture.
6146 void generateInfoForComponentList(
6147 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6148 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006149 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006150 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
6151 bool IsFirstComponentList) const {
6152
6153 // The following summarizes what has to be generated for each map and the
6154 // types bellow. The generated information is expressed in this order:
6155 // base pointer, section pointer, size, flags
6156 // (to add to the ones that come from the map type and modifier).
6157 //
6158 // double d;
6159 // int i[100];
6160 // float *p;
6161 //
6162 // struct S1 {
6163 // int i;
6164 // float f[50];
6165 // }
6166 // struct S2 {
6167 // int i;
6168 // float f[50];
6169 // S1 s;
6170 // double *p;
6171 // struct S2 *ps;
6172 // }
6173 // S2 s;
6174 // S2 *ps;
6175 //
6176 // map(d)
6177 // &d, &d, sizeof(double), noflags
6178 //
6179 // map(i)
6180 // &i, &i, 100*sizeof(int), noflags
6181 //
6182 // map(i[1:23])
6183 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6184 //
6185 // map(p)
6186 // &p, &p, sizeof(float*), noflags
6187 //
6188 // map(p[1:24])
6189 // p, &p[1], 24*sizeof(float), noflags
6190 //
6191 // map(s)
6192 // &s, &s, sizeof(S2), noflags
6193 //
6194 // map(s.i)
6195 // &s, &(s.i), sizeof(int), noflags
6196 //
6197 // map(s.s.f)
6198 // &s, &(s.i.f), 50*sizeof(int), noflags
6199 //
6200 // map(s.p)
6201 // &s, &(s.p), sizeof(double*), noflags
6202 //
6203 // map(s.p[:22], s.a s.b)
6204 // &s, &(s.p), sizeof(double*), noflags
6205 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
6206 //
6207 // map(s.ps)
6208 // &s, &(s.ps), sizeof(S2*), noflags
6209 //
6210 // map(s.ps->s.i)
6211 // &s, &(s.ps), sizeof(S2*), noflags
6212 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
6213 //
6214 // map(s.ps->ps)
6215 // &s, &(s.ps), sizeof(S2*), noflags
6216 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6217 //
6218 // map(s.ps->ps->ps)
6219 // &s, &(s.ps), sizeof(S2*), noflags
6220 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6221 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6222 //
6223 // map(s.ps->ps->s.f[:22])
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->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
6227 //
6228 // map(ps)
6229 // &ps, &ps, sizeof(S2*), noflags
6230 //
6231 // map(ps->i)
6232 // ps, &(ps->i), sizeof(int), noflags
6233 //
6234 // map(ps->s.f)
6235 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6236 //
6237 // map(ps->p)
6238 // ps, &(ps->p), sizeof(double*), noflags
6239 //
6240 // map(ps->p[:22])
6241 // ps, &(ps->p), sizeof(double*), noflags
6242 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
6243 //
6244 // map(ps->ps)
6245 // ps, &(ps->ps), sizeof(S2*), noflags
6246 //
6247 // map(ps->ps->s.i)
6248 // ps, &(ps->ps), sizeof(S2*), noflags
6249 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
6250 //
6251 // map(ps->ps->ps)
6252 // ps, &(ps->ps), sizeof(S2*), noflags
6253 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6254 //
6255 // map(ps->ps->ps->ps)
6256 // ps, &(ps->ps), sizeof(S2*), noflags
6257 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6258 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6259 //
6260 // map(ps->ps->ps->s.f[:22])
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->s.f[0]), 22*sizeof(float), ptr_flag +
6264 // extra_flag
6265
6266 // Track if the map information being generated is the first for a capture.
6267 bool IsCaptureFirstInfo = IsFirstComponentList;
6268
6269 // Scan the components from the base to the complete expression.
6270 auto CI = Components.rbegin();
6271 auto CE = Components.rend();
6272 auto I = CI;
6273
6274 // Track if the map information being generated is the first for a list of
6275 // components.
6276 bool IsExpressionFirstInfo = true;
6277 llvm::Value *BP = nullptr;
6278
6279 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6280 // The base is the 'this' pointer. The content of the pointer is going
6281 // to be the base of the field being mapped.
6282 BP = CGF.EmitScalarExpr(ME->getBase());
6283 } else {
6284 // The base is the reference to the variable.
6285 // BP = &Var.
6286 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
6287 .getPointer();
6288
6289 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006290 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006291 // reference. References are ignored for mapping purposes.
6292 QualType Ty =
6293 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6294 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6295 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006296 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006297 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006298 .getPointer();
6299
6300 // We do not need to generate individual map information for the
6301 // pointer, it can be associated with the combined storage.
6302 ++I;
6303 }
6304 }
6305
6306 for (; I != CE; ++I) {
6307 auto Next = std::next(I);
6308
6309 // We need to generate the addresses and sizes if this is the last
6310 // component, if the component is a pointer or if it is an array section
6311 // whose length can't be proved to be one. If this is a pointer, it
6312 // becomes the base address for the following components.
6313
6314 // A final array section, is one whose length can't be proved to be one.
6315 bool IsFinalArraySection =
6316 isFinalArraySectionExpression(I->getAssociatedExpression());
6317
6318 // Get information on whether the element is a pointer. Have to do a
6319 // special treatment for array sections given that they are built-in
6320 // types.
6321 const auto *OASE =
6322 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6323 bool IsPointer =
6324 (OASE &&
6325 OMPArraySectionExpr::getBaseOriginalType(OASE)
6326 .getCanonicalType()
6327 ->isAnyPointerType()) ||
6328 I->getAssociatedExpression()->getType()->isAnyPointerType();
6329
6330 if (Next == CE || IsPointer || IsFinalArraySection) {
6331
6332 // If this is not the last component, we expect the pointer to be
6333 // associated with an array expression or member expression.
6334 assert((Next == CE ||
6335 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6336 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6337 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6338 "Unexpected expression");
6339
Samuel Antao86ace552016-04-27 22:40:57 +00006340 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
6341 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6342
Samuel Antao03a3cec2016-07-27 22:52:16 +00006343 // If we have a member expression and the current component is a
6344 // reference, we have to map the reference too. Whenever we have a
6345 // reference, the section that reference refers to is going to be a
6346 // load instruction from the storage assigned to the reference.
6347 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6348 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6349 auto *LI = cast<llvm::LoadInst>(LB);
6350 auto *RefAddr = LI->getPointerOperand();
6351
6352 BasePointers.push_back(BP);
6353 Pointers.push_back(RefAddr);
6354 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6355 Types.push_back(getMapTypeBits(
6356 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
6357 !IsExpressionFirstInfo, IsCaptureFirstInfo));
6358 IsExpressionFirstInfo = false;
6359 IsCaptureFirstInfo = false;
6360 // The reference will be the next base address.
6361 BP = RefAddr;
6362 }
6363
6364 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006365 Pointers.push_back(LB);
6366 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006367
Samuel Antao6782e942016-05-26 16:48:10 +00006368 // We need to add a pointer flag for each map that comes from the
6369 // same expression except for the first one. We also need to signal
6370 // this map is the first one that relates with the current capture
6371 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00006372 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
6373 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00006374 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006375
6376 // If we have a final array section, we are done with this expression.
6377 if (IsFinalArraySection)
6378 break;
6379
6380 // The pointer becomes the base for the next element.
6381 if (Next != CE)
6382 BP = LB;
6383
6384 IsExpressionFirstInfo = false;
6385 IsCaptureFirstInfo = false;
6386 continue;
6387 }
6388 }
6389 }
6390
Samuel Antaod486f842016-05-26 16:53:38 +00006391 /// \brief Return the adjusted map modifiers if the declaration a capture
6392 /// refers to appears in a first-private clause. This is expected to be used
6393 /// only with directives that start with 'target'.
6394 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6395 unsigned CurrentModifiers) {
6396 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6397
6398 // A first private variable captured by reference will use only the
6399 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6400 // declaration is known as first-private in this handler.
6401 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6402 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
6403 MappableExprsHandler::OMP_MAP_TO;
6404
6405 // We didn't modify anything.
6406 return CurrentModifiers;
6407 }
6408
Samuel Antao86ace552016-04-27 22:40:57 +00006409public:
6410 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006411 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006412 // Extract firstprivate clause information.
6413 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6414 for (const auto *D : C->varlists())
6415 FirstPrivateDecls.insert(
6416 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006417 // Extract device pointer clause information.
6418 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6419 for (auto L : C->component_lists())
6420 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006421 }
Samuel Antao86ace552016-04-27 22:40:57 +00006422
6423 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006424 /// types for the extracted mappable expressions. Also, for each item that
6425 /// relates with a device pointer, a pair of the relevant declaration and
6426 /// index where it occurs is appended to the device pointers info array.
6427 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006428 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6429 MapFlagsArrayTy &Types) const {
6430 BasePointers.clear();
6431 Pointers.clear();
6432 Sizes.clear();
6433 Types.clear();
6434
6435 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006436 /// Kind that defines how a device pointer has to be returned.
6437 enum ReturnPointerKind {
6438 // Don't have to return any pointer.
6439 RPK_None,
6440 // Pointer is the base of the declaration.
6441 RPK_Base,
6442 // Pointer is a member of the base declaration - 'this'
6443 RPK_Member,
6444 // Pointer is a reference and a member of the base declaration - 'this'
6445 RPK_MemberReference,
6446 };
Samuel Antao86ace552016-04-27 22:40:57 +00006447 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006448 OpenMPMapClauseKind MapType;
6449 OpenMPMapClauseKind MapTypeModifier;
6450 ReturnPointerKind ReturnDevicePointer;
6451
6452 MapInfo()
6453 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
6454 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00006455 MapInfo(
6456 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6457 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6458 ReturnPointerKind ReturnDevicePointer)
6459 : Components(Components), MapType(MapType),
6460 MapTypeModifier(MapTypeModifier),
6461 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006462 };
6463
6464 // We have to process the component lists that relate with the same
6465 // declaration in a single chunk so that we can generate the map flags
6466 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006467 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006468
6469 // Helper function to fill the information map for the different supported
6470 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006471 auto &&InfoGen = [&Info](
6472 const ValueDecl *D,
6473 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6474 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006475 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006476 const ValueDecl *VD =
6477 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
6478 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
6479 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006480
Paul Robinson78fb1322016-08-01 22:12:46 +00006481 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006482 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006483 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006484 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
6485 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006486 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006487 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006488 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
6489 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006490 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006491 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006492 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
6493 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00006494
Samuel Antaocc10b852016-07-28 14:23:26 +00006495 // Look at the use_device_ptr clause information and mark the existing map
6496 // entries as such. If there is no map information for an entry in the
6497 // use_device_ptr list, we create one with map type 'alloc' and zero size
6498 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006499 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006500 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006501 for (auto L : C->component_lists()) {
6502 assert(!L.second.empty() && "Not expecting empty list of components!");
6503 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6504 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6505 auto *IE = L.second.back().getAssociatedExpression();
6506 // If the first component is a member expression, we have to look into
6507 // 'this', which maps to null in the map of map information. Otherwise
6508 // look directly for the information.
6509 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6510
6511 // We potentially have map information for this declaration already.
6512 // Look for the first set of components that refer to it.
6513 if (It != Info.end()) {
6514 auto CI = std::find_if(
6515 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6516 return MI.Components.back().getAssociatedDeclaration() == VD;
6517 });
6518 // If we found a map entry, signal that the pointer has to be returned
6519 // and move on to the next declaration.
6520 if (CI != It->second.end()) {
6521 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6522 ? (VD->getType()->isReferenceType()
6523 ? MapInfo::RPK_MemberReference
6524 : MapInfo::RPK_Member)
6525 : MapInfo::RPK_Base;
6526 continue;
6527 }
6528 }
6529
6530 // We didn't find any match in our map information - generate a zero
6531 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006532 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006533 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006534 this->CGF
6535 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006536 .getScalarVal();
6537 BasePointers.push_back({Ptr, VD});
6538 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006539 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00006540 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6541 }
6542
Samuel Antao86ace552016-04-27 22:40:57 +00006543 for (auto &M : Info) {
6544 // We need to know when we generate information for the first component
6545 // associated with a capture, because the mapping flags depend on it.
6546 bool IsFirstComponentList = true;
6547 for (MapInfo &L : M.second) {
6548 assert(!L.Components.empty() &&
6549 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006550
6551 // Remember the current base pointer index.
6552 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006553 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00006554 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
6555 L.Components, BasePointers, Pointers,
6556 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00006557
6558 // If this entry relates with a device pointer, set the relevant
6559 // declaration and add the 'return pointer' flag.
6560 if (IsFirstComponentList &&
6561 L.ReturnDevicePointer != MapInfo::RPK_None) {
6562 // If the pointer is not the base of the map, we need to skip the
6563 // base. If it is a reference in a member field, we also need to skip
6564 // the map of the reference.
6565 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6566 ++CurrentBasePointersIdx;
6567 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6568 ++CurrentBasePointersIdx;
6569 }
6570 assert(BasePointers.size() > CurrentBasePointersIdx &&
6571 "Unexpected number of mapped base pointers.");
6572
6573 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6574 assert(RelevantVD &&
6575 "No relevant declaration related with device pointer??");
6576
6577 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6578 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6579 }
Samuel Antao86ace552016-04-27 22:40:57 +00006580 IsFirstComponentList = false;
6581 }
6582 }
6583 }
6584
6585 /// \brief Generate the base pointers, section pointers, sizes and map types
6586 /// associated to a given capture.
6587 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006588 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006589 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006590 MapValuesArrayTy &Pointers,
6591 MapValuesArrayTy &Sizes,
6592 MapFlagsArrayTy &Types) const {
6593 assert(!Cap->capturesVariableArrayType() &&
6594 "Not expecting to generate map info for a variable array type!");
6595
6596 BasePointers.clear();
6597 Pointers.clear();
6598 Sizes.clear();
6599 Types.clear();
6600
Samuel Antao6890b092016-07-28 14:25:09 +00006601 // We need to know when we generating information for the first component
6602 // associated with a capture, because the mapping flags depend on it.
6603 bool IsFirstComponentList = true;
6604
Samuel Antao86ace552016-04-27 22:40:57 +00006605 const ValueDecl *VD =
6606 Cap->capturesThis()
6607 ? nullptr
6608 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6609
Samuel Antao6890b092016-07-28 14:25:09 +00006610 // If this declaration appears in a is_device_ptr clause we just have to
6611 // pass the pointer by value. If it is a reference to a declaration, we just
6612 // pass its value, otherwise, if it is a member expression, we need to map
6613 // 'to' the field.
6614 if (!VD) {
6615 auto It = DevPointersMap.find(VD);
6616 if (It != DevPointersMap.end()) {
6617 for (auto L : It->second) {
6618 generateInfoForComponentList(
6619 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
6620 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
6621 IsFirstComponentList = false;
6622 }
6623 return;
6624 }
6625 } else if (DevPointersMap.count(VD)) {
6626 BasePointers.push_back({Arg, VD});
6627 Pointers.push_back(Arg);
6628 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6629 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6630 return;
6631 }
6632
Paul Robinson78fb1322016-08-01 22:12:46 +00006633 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006634 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006635 for (auto L : C->decl_component_lists(VD)) {
6636 assert(L.first == VD &&
6637 "We got information for the wrong declaration??");
6638 assert(!L.second.empty() &&
6639 "Not expecting declaration with no component lists.");
6640 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
6641 L.second, BasePointers, Pointers, Sizes,
6642 Types, IsFirstComponentList);
6643 IsFirstComponentList = false;
6644 }
6645
6646 return;
6647 }
Samuel Antaod486f842016-05-26 16:53:38 +00006648
6649 /// \brief Generate the default map information for a given capture \a CI,
6650 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006651 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6652 const FieldDecl &RI, llvm::Value *CV,
6653 MapBaseValuesArrayTy &CurBasePointers,
6654 MapValuesArrayTy &CurPointers,
6655 MapValuesArrayTy &CurSizes,
6656 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006657
6658 // Do the default mapping.
6659 if (CI.capturesThis()) {
6660 CurBasePointers.push_back(CV);
6661 CurPointers.push_back(CV);
6662 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6663 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6664 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006665 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006666 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006667 CurBasePointers.push_back(CV);
6668 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006669 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006670 // We have to signal to the runtime captures passed by value that are
6671 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00006672 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006673 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6674 } else {
6675 // Pointers are implicitly mapped with a zero size and no flags
6676 // (other than first map that is added for all implicit maps).
6677 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006678 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6679 }
6680 } else {
6681 assert(CI.capturesVariable() && "Expected captured reference.");
6682 CurBasePointers.push_back(CV);
6683 CurPointers.push_back(CV);
6684
6685 const ReferenceType *PtrTy =
6686 cast<ReferenceType>(RI.getType().getTypePtr());
6687 QualType ElementType = PtrTy->getPointeeType();
6688 CurSizes.push_back(CGF.getTypeSize(ElementType));
6689 // The default map type for a scalar/complex type is 'to' because by
6690 // default the value doesn't have to be retrieved. For an aggregate
6691 // type, the default is 'tofrom'.
6692 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006693 ? (OMP_MAP_TO | OMP_MAP_FROM)
6694 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006695
6696 // If we have a capture by reference we may need to add the private
6697 // pointer flag if the base declaration shows in some first-private
6698 // clause.
6699 CurMapTypes.back() =
6700 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6701 }
6702 // Every default map produces a single argument, so, it is always the
6703 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00006704 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00006705 }
Samuel Antao86ace552016-04-27 22:40:57 +00006706};
Samuel Antaodf158d52016-04-27 22:58:19 +00006707
6708enum OpenMPOffloadingReservedDeviceIDs {
6709 /// \brief Device ID if the device was not defined, runtime should get it
6710 /// from environment variables in the spec.
6711 OMP_DEVICEID_UNDEF = -1,
6712};
6713} // anonymous namespace
6714
6715/// \brief Emit the arrays used to pass the captures and map information to the
6716/// offloading runtime library. If there is no map or capture information,
6717/// return nullptr by reference.
6718static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006719emitOffloadingArrays(CodeGenFunction &CGF,
6720 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006721 MappableExprsHandler::MapValuesArrayTy &Pointers,
6722 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006723 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6724 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006725 auto &CGM = CGF.CGM;
6726 auto &Ctx = CGF.getContext();
6727
Samuel Antaocc10b852016-07-28 14:23:26 +00006728 // Reset the array information.
6729 Info.clearArrayInfo();
6730 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006731
Samuel Antaocc10b852016-07-28 14:23:26 +00006732 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006733 // Detect if we have any capture size requiring runtime evaluation of the
6734 // size so that a constant array could be eventually used.
6735 bool hasRuntimeEvaluationCaptureSize = false;
6736 for (auto *S : Sizes)
6737 if (!isa<llvm::Constant>(S)) {
6738 hasRuntimeEvaluationCaptureSize = true;
6739 break;
6740 }
6741
Samuel Antaocc10b852016-07-28 14:23:26 +00006742 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006743 QualType PointerArrayType =
6744 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6745 /*IndexTypeQuals=*/0);
6746
Samuel Antaocc10b852016-07-28 14:23:26 +00006747 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006748 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006749 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006750 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6751
6752 // If we don't have any VLA types or other types that require runtime
6753 // evaluation, we can use a constant array for the map sizes, otherwise we
6754 // need to fill up the arrays as we do for the pointers.
6755 if (hasRuntimeEvaluationCaptureSize) {
6756 QualType SizeArrayType = Ctx.getConstantArrayType(
6757 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6758 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006759 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006760 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6761 } else {
6762 // We expect all the sizes to be constant, so we collect them to create
6763 // a constant array.
6764 SmallVector<llvm::Constant *, 16> ConstSizes;
6765 for (auto S : Sizes)
6766 ConstSizes.push_back(cast<llvm::Constant>(S));
6767
6768 auto *SizesArrayInit = llvm::ConstantArray::get(
6769 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6770 auto *SizesArrayGbl = new llvm::GlobalVariable(
6771 CGM.getModule(), SizesArrayInit->getType(),
6772 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6773 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006774 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006775 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006776 }
6777
6778 // The map types are always constant so we don't need to generate code to
6779 // fill arrays. Instead, we create an array constant.
6780 llvm::Constant *MapTypesArrayInit =
6781 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6782 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6783 CGM.getModule(), MapTypesArrayInit->getType(),
6784 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6785 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006786 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006787 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006788
Samuel Antaocc10b852016-07-28 14:23:26 +00006789 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6790 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006791 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006792 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6793 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006794 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6795 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006796 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6797 CGF.Builder.CreateStore(BPVal, BPAddr);
6798
Samuel Antaocc10b852016-07-28 14:23:26 +00006799 if (Info.requiresDevicePointerInfo())
6800 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6801 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6802
Samuel Antaodf158d52016-04-27 22:58:19 +00006803 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006804 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006805 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6806 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006807 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6808 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006809 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6810 CGF.Builder.CreateStore(PVal, PAddr);
6811
6812 if (hasRuntimeEvaluationCaptureSize) {
6813 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006814 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6815 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006816 /*Idx0=*/0,
6817 /*Idx1=*/i);
6818 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6819 CGF.Builder.CreateStore(
6820 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6821 SAddr);
6822 }
6823 }
6824 }
6825}
6826/// \brief Emit the arguments to be passed to the runtime library based on the
6827/// arrays of pointers, sizes and map types.
6828static void emitOffloadingArraysArgument(
6829 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6830 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006831 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006832 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006833 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006834 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006835 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6836 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006837 /*Idx0=*/0, /*Idx1=*/0);
6838 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006839 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6840 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006841 /*Idx0=*/0,
6842 /*Idx1=*/0);
6843 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006844 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006845 /*Idx0=*/0, /*Idx1=*/0);
6846 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006847 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6848 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006849 /*Idx0=*/0,
6850 /*Idx1=*/0);
6851 } else {
6852 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6853 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6854 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6855 MapTypesArrayArg =
6856 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6857 }
Samuel Antao86ace552016-04-27 22:40:57 +00006858}
6859
Samuel Antaobed3c462015-10-02 16:14:20 +00006860void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6861 const OMPExecutableDirective &D,
6862 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006863 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006864 const Expr *IfCond, const Expr *Device,
6865 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006866 if (!CGF.HaveInsertPoint())
6867 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006868
Samuel Antaoee8fb302016-01-06 13:42:12 +00006869 assert(OutlinedFn && "Invalid outlined function!");
6870
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006871 auto &Ctx = CGF.getContext();
6872
Samuel Antao86ace552016-04-27 22:40:57 +00006873 // Fill up the arrays with all the captured variables.
6874 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006875 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006876 MappableExprsHandler::MapValuesArrayTy Pointers;
6877 MappableExprsHandler::MapValuesArrayTy Sizes;
6878 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006879
Samuel Antaocc10b852016-07-28 14:23:26 +00006880 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006881 MappableExprsHandler::MapValuesArrayTy CurPointers;
6882 MappableExprsHandler::MapValuesArrayTy CurSizes;
6883 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6884
Samuel Antaod486f842016-05-26 16:53:38 +00006885 // Get mappable expression information.
6886 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006887
6888 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6889 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006890 auto CV = CapturedVars.begin();
6891 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6892 CE = CS.capture_end();
6893 CI != CE; ++CI, ++RI, ++CV) {
6894 StringRef Name;
6895 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00006896
Samuel Antao86ace552016-04-27 22:40:57 +00006897 CurBasePointers.clear();
6898 CurPointers.clear();
6899 CurSizes.clear();
6900 CurMapTypes.clear();
6901
6902 // VLA sizes are passed to the outlined region by copy and do not have map
6903 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006904 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006905 CurBasePointers.push_back(*CV);
6906 CurPointers.push_back(*CV);
6907 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006908 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006909 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6910 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006911 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006912 // If we have any information in the map clause, we use it, otherwise we
6913 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006914 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006915 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006916 if (CurBasePointers.empty())
6917 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6918 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006919 }
Samuel Antao86ace552016-04-27 22:40:57 +00006920 // We expect to have at least an element of information for this capture.
6921 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6922 assert(CurBasePointers.size() == CurPointers.size() &&
6923 CurBasePointers.size() == CurSizes.size() &&
6924 CurBasePointers.size() == CurMapTypes.size() &&
6925 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006926
Samuel Antao86ace552016-04-27 22:40:57 +00006927 // The kernel args are always the first elements of the base pointers
6928 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006929 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006930 // We need to append the results of this capture to what we already have.
6931 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6932 Pointers.append(CurPointers.begin(), CurPointers.end());
6933 Sizes.append(CurSizes.begin(), CurSizes.end());
6934 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006935 }
6936
6937 // Keep track on whether the host function has to be executed.
6938 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006939 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006940 auto OffloadError = CGF.MakeAddrLValue(
6941 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6942 OffloadErrorQType);
6943 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6944 OffloadError);
6945
6946 // Fill up the pointer arrays and transfer execution to the device.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006947 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6948 OutlinedFnID, OffloadError,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006949 &D](CodeGenFunction &CGF, PrePostActionTy &) {
6950 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006951 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006952 TargetDataInfo Info;
6953 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6954 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6955 Info.PointersArray, Info.SizesArray,
6956 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006957
6958 // On top of the arrays that were filled up, the target offloading call
6959 // takes as arguments the device id as well as the host pointer. The host
6960 // pointer is used by the runtime library to identify the current target
6961 // region, so it only has to be unique and not necessarily point to
6962 // anything. It could be the pointer to the outlined function that
6963 // implements the target region, but we aren't using that so that the
6964 // compiler doesn't need to keep that, and could therefore inline the host
6965 // function if proven worthwhile during optimization.
6966
Samuel Antaoee8fb302016-01-06 13:42:12 +00006967 // From this point on, we need to have an ID of the target region defined.
6968 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006969
6970 // Emit device ID if any.
6971 llvm::Value *DeviceID;
6972 if (Device)
6973 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006974 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006975 else
6976 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6977
Samuel Antaodf158d52016-04-27 22:58:19 +00006978 // Emit the number of elements in the offloading arrays.
6979 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6980
Samuel Antaob68e2db2016-03-03 16:20:23 +00006981 // Return value of the runtime offloading call.
6982 llvm::Value *Return;
6983
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006984 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6985 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006986
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006987 // The target region is an outlined function launched by the runtime
6988 // via calls __tgt_target() or __tgt_target_teams().
6989 //
6990 // __tgt_target() launches a target region with one team and one thread,
6991 // executing a serial region. This master thread may in turn launch
6992 // more threads within its team upon encountering a parallel region,
6993 // however, no additional teams can be launched on the device.
6994 //
6995 // __tgt_target_teams() launches a target region with one or more teams,
6996 // each with one or more threads. This call is required for target
6997 // constructs such as:
6998 // 'target teams'
6999 // 'target' / 'teams'
7000 // 'target teams distribute parallel for'
7001 // 'target parallel'
7002 // and so on.
7003 //
7004 // Note that on the host and CPU targets, the runtime implementation of
7005 // these calls simply call the outlined function without forking threads.
7006 // The outlined functions themselves have runtime calls to
7007 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7008 // the compiler in emitTeamsCall() and emitParallelCall().
7009 //
7010 // In contrast, on the NVPTX target, the implementation of
7011 // __tgt_target_teams() launches a GPU kernel with the requested number
7012 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007013 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007014 // If we have NumTeams defined this means that we have an enclosed teams
7015 // region. Therefore we also expect to have NumThreads defined. These two
7016 // values should be defined in the presence of a teams directive,
7017 // regardless of having any clauses associated. If the user is using teams
7018 // but no clauses, these two values will be the default that should be
7019 // passed to the runtime library - a 32-bit integer with the value zero.
7020 assert(NumThreads && "Thread limit expression should be available along "
7021 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007022 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007023 DeviceID, OutlinedFnID,
7024 PointerNum, Info.BasePointersArray,
7025 Info.PointersArray, Info.SizesArray,
7026 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007027 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007028 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007029 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007030 } else {
7031 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007032 DeviceID, OutlinedFnID,
7033 PointerNum, Info.BasePointersArray,
7034 Info.PointersArray, Info.SizesArray,
7035 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007036 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007037 OffloadingArgs);
7038 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007039
7040 CGF.EmitStoreOfScalar(Return, OffloadError);
7041 };
7042
Samuel Antaoee8fb302016-01-06 13:42:12 +00007043 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007044 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
7045 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00007046 OffloadError);
7047 };
7048
7049 // If we have a target function ID it means that we need to support
7050 // offloading, otherwise, just execute on the host. We need to execute on host
7051 // regardless of the conditional in the if clause if, e.g., the user do not
7052 // specify target triples.
7053 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007054 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007055 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007056 else {
7057 RegionCodeGenTy ThenRCG(ThenGen);
7058 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007059 }
7060 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007061 RegionCodeGenTy ElseRCG(ElseGen);
7062 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007063 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007064
7065 // Check the error code and execute the host version if required.
7066 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
7067 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
7068 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
7069 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
7070 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7071
7072 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev3c595a62017-08-14 15:01:03 +00007073 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00007074 CGF.EmitBranch(OffloadContBlock);
7075
7076 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007077}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007078
7079void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7080 StringRef ParentName) {
7081 if (!S)
7082 return;
7083
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007084 // Codegen OMP target directives that offload compute to the device.
7085 bool requiresDeviceCodegen =
7086 isa<OMPExecutableDirective>(S) &&
7087 isOpenMPTargetExecutionDirective(
7088 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007089
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007090 if (requiresDeviceCodegen) {
7091 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007092 unsigned DeviceID;
7093 unsigned FileID;
7094 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007095 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007096 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007097
7098 // Is this a target region that should not be emitted as an entry point? If
7099 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007100 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7101 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007102 return;
7103
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007104 switch (S->getStmtClass()) {
7105 case Stmt::OMPTargetDirectiveClass:
7106 CodeGenFunction::EmitOMPTargetDeviceFunction(
7107 CGM, ParentName, cast<OMPTargetDirective>(*S));
7108 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007109 case Stmt::OMPTargetParallelDirectiveClass:
7110 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7111 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7112 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007113 case Stmt::OMPTargetTeamsDirectiveClass:
7114 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7115 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7116 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007117 default:
7118 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7119 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007120 return;
7121 }
7122
7123 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007124 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007125 return;
7126
7127 scanForTargetRegionsFunctions(
7128 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7129 ParentName);
7130 return;
7131 }
7132
7133 // If this is a lambda function, look into its body.
7134 if (auto *L = dyn_cast<LambdaExpr>(S))
7135 S = L->getBody();
7136
7137 // Keep looking for target regions recursively.
7138 for (auto *II : S->children())
7139 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007140}
7141
7142bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7143 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7144
7145 // If emitting code for the host, we do not process FD here. Instead we do
7146 // the normal code generation.
7147 if (!CGM.getLangOpts().OpenMPIsDevice)
7148 return false;
7149
7150 // Try to detect target regions in the function.
7151 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7152
Samuel Antao4b75b872016-12-12 19:26:31 +00007153 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007154 // scanning. Therefore, we signal that this function is completely dealt
7155 // with.
7156 return true;
7157}
7158
7159bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7160 if (!CGM.getLangOpts().OpenMPIsDevice)
7161 return false;
7162
7163 // Check if there are Ctors/Dtors in this declaration and look for target
7164 // regions in it. We use the complete variant to produce the kernel name
7165 // mangling.
7166 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7167 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7168 for (auto *Ctor : RD->ctors()) {
7169 StringRef ParentName =
7170 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7171 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7172 }
7173 auto *Dtor = RD->getDestructor();
7174 if (Dtor) {
7175 StringRef ParentName =
7176 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7177 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7178 }
7179 }
7180
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007181 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007182 // implemented yet). Therefore we signal that GD was processed in this case.
7183 return true;
7184}
7185
7186bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7187 auto *VD = GD.getDecl();
7188 if (isa<FunctionDecl>(VD))
7189 return emitTargetFunctions(GD);
7190
7191 return emitTargetGlobalVariable(GD);
7192}
7193
7194llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7195 // If we have offloading in the current module, we need to emit the entries
7196 // now and register the offloading descriptor.
7197 createOffloadEntriesAndInfoMetadata();
7198
7199 // Create and register the offloading binary descriptors. This is the main
7200 // entity that captures all the information about offloading in the current
7201 // compilation unit.
7202 return createOffloadingBinaryDescriptorRegistration();
7203}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007204
7205void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7206 const OMPExecutableDirective &D,
7207 SourceLocation Loc,
7208 llvm::Value *OutlinedFn,
7209 ArrayRef<llvm::Value *> CapturedVars) {
7210 if (!CGF.HaveInsertPoint())
7211 return;
7212
7213 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7214 CodeGenFunction::RunCleanupsScope Scope(CGF);
7215
7216 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7217 llvm::Value *Args[] = {
7218 RTLoc,
7219 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7220 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7221 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7222 RealArgs.append(std::begin(Args), std::end(Args));
7223 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7224
7225 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7226 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7227}
7228
7229void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007230 const Expr *NumTeams,
7231 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007232 SourceLocation Loc) {
7233 if (!CGF.HaveInsertPoint())
7234 return;
7235
7236 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7237
Carlo Bertollic6872252016-04-04 15:55:02 +00007238 llvm::Value *NumTeamsVal =
7239 (NumTeams)
7240 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7241 CGF.CGM.Int32Ty, /* isSigned = */ true)
7242 : CGF.Builder.getInt32(0);
7243
7244 llvm::Value *ThreadLimitVal =
7245 (ThreadLimit)
7246 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7247 CGF.CGM.Int32Ty, /* isSigned = */ true)
7248 : CGF.Builder.getInt32(0);
7249
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007250 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007251 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7252 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007253 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7254 PushNumTeamsArgs);
7255}
Samuel Antaodf158d52016-04-27 22:58:19 +00007256
Samuel Antaocc10b852016-07-28 14:23:26 +00007257void CGOpenMPRuntime::emitTargetDataCalls(
7258 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7259 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007260 if (!CGF.HaveInsertPoint())
7261 return;
7262
Samuel Antaocc10b852016-07-28 14:23:26 +00007263 // Action used to replace the default codegen action and turn privatization
7264 // off.
7265 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007266
7267 // Generate the code for the opening of the data environment. Capture all the
7268 // arguments of the runtime call by reference because they are used in the
7269 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007270 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7271 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007272 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007273 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007274 MappableExprsHandler::MapValuesArrayTy Pointers;
7275 MappableExprsHandler::MapValuesArrayTy Sizes;
7276 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7277
7278 // Get map clause information.
7279 MappableExprsHandler MCHandler(D, CGF);
7280 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007281
7282 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007283 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007284
7285 llvm::Value *BasePointersArrayArg = nullptr;
7286 llvm::Value *PointersArrayArg = nullptr;
7287 llvm::Value *SizesArrayArg = nullptr;
7288 llvm::Value *MapTypesArrayArg = nullptr;
7289 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007290 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007291
7292 // Emit device ID if any.
7293 llvm::Value *DeviceID = nullptr;
7294 if (Device)
7295 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7296 CGF.Int32Ty, /*isSigned=*/true);
7297 else
7298 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7299
7300 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007301 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007302
7303 llvm::Value *OffloadingArgs[] = {
7304 DeviceID, PointerNum, BasePointersArrayArg,
7305 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7306 auto &RT = CGF.CGM.getOpenMPRuntime();
7307 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7308 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007309
7310 // If device pointer privatization is required, emit the body of the region
7311 // here. It will have to be duplicated: with and without privatization.
7312 if (!Info.CaptureDeviceAddrMap.empty())
7313 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007314 };
7315
7316 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007317 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007318 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007319
7320 llvm::Value *BasePointersArrayArg = nullptr;
7321 llvm::Value *PointersArrayArg = nullptr;
7322 llvm::Value *SizesArrayArg = nullptr;
7323 llvm::Value *MapTypesArrayArg = nullptr;
7324 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007325 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007326
7327 // Emit device ID if any.
7328 llvm::Value *DeviceID = nullptr;
7329 if (Device)
7330 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7331 CGF.Int32Ty, /*isSigned=*/true);
7332 else
7333 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7334
7335 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007336 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007337
7338 llvm::Value *OffloadingArgs[] = {
7339 DeviceID, PointerNum, BasePointersArrayArg,
7340 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7341 auto &RT = CGF.CGM.getOpenMPRuntime();
7342 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7343 OffloadingArgs);
7344 };
7345
Samuel Antaocc10b852016-07-28 14:23:26 +00007346 // If we need device pointer privatization, we need to emit the body of the
7347 // region with no privatization in the 'else' branch of the conditional.
7348 // Otherwise, we don't have to do anything.
7349 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7350 PrePostActionTy &) {
7351 if (!Info.CaptureDeviceAddrMap.empty()) {
7352 CodeGen.setAction(NoPrivAction);
7353 CodeGen(CGF);
7354 }
7355 };
7356
7357 // We don't have to do anything to close the region if the if clause evaluates
7358 // to false.
7359 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007360
7361 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007362 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007363 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007364 RegionCodeGenTy RCG(BeginThenGen);
7365 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007366 }
7367
Samuel Antaocc10b852016-07-28 14:23:26 +00007368 // If we don't require privatization of device pointers, we emit the body in
7369 // between the runtime calls. This avoids duplicating the body code.
7370 if (Info.CaptureDeviceAddrMap.empty()) {
7371 CodeGen.setAction(NoPrivAction);
7372 CodeGen(CGF);
7373 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007374
7375 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007376 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007377 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007378 RegionCodeGenTy RCG(EndThenGen);
7379 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007380 }
7381}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007382
Samuel Antao8d2d7302016-05-26 18:30:22 +00007383void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007384 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7385 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007386 if (!CGF.HaveInsertPoint())
7387 return;
7388
Samuel Antao8dd66282016-04-27 23:14:30 +00007389 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007390 isa<OMPTargetExitDataDirective>(D) ||
7391 isa<OMPTargetUpdateDirective>(D)) &&
7392 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007393
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007394 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007395 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007396 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007397 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007398 MappableExprsHandler::MapValuesArrayTy Pointers;
7399 MappableExprsHandler::MapValuesArrayTy Sizes;
7400 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7401
7402 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007403 MappableExprsHandler MEHandler(D, CGF);
7404 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007405
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007406 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007407 TargetDataInfo Info;
7408 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7409 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7410 Info.PointersArray, Info.SizesArray,
7411 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007412
7413 // Emit device ID if any.
7414 llvm::Value *DeviceID = nullptr;
7415 if (Device)
7416 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7417 CGF.Int32Ty, /*isSigned=*/true);
7418 else
7419 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7420
7421 // Emit the number of elements in the offloading arrays.
7422 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7423
7424 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007425 DeviceID, PointerNum, Info.BasePointersArray,
7426 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007427
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007428 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007429 // Select the right runtime function call for each expected standalone
7430 // directive.
7431 OpenMPRTLFunction RTLFn;
7432 switch (D.getDirectiveKind()) {
7433 default:
7434 llvm_unreachable("Unexpected standalone target data directive.");
7435 break;
7436 case OMPD_target_enter_data:
7437 RTLFn = OMPRTL__tgt_target_data_begin;
7438 break;
7439 case OMPD_target_exit_data:
7440 RTLFn = OMPRTL__tgt_target_data_end;
7441 break;
7442 case OMPD_target_update:
7443 RTLFn = OMPRTL__tgt_target_data_update;
7444 break;
7445 }
7446 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007447 };
7448
7449 // In the event we get an if clause, we don't have to take any action on the
7450 // else side.
7451 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7452
7453 if (IfCond) {
7454 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7455 } else {
7456 RegionCodeGenTy ThenGenRCG(ThenGen);
7457 ThenGenRCG(CGF);
7458 }
7459}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007460
7461namespace {
7462 /// Kind of parameter in a function with 'declare simd' directive.
7463 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7464 /// Attribute set of the parameter.
7465 struct ParamAttrTy {
7466 ParamKindTy Kind = Vector;
7467 llvm::APSInt StrideOrArg;
7468 llvm::APSInt Alignment;
7469 };
7470} // namespace
7471
7472static unsigned evaluateCDTSize(const FunctionDecl *FD,
7473 ArrayRef<ParamAttrTy> ParamAttrs) {
7474 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7475 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7476 // of that clause. The VLEN value must be power of 2.
7477 // In other case the notion of the function`s "characteristic data type" (CDT)
7478 // is used to compute the vector length.
7479 // CDT is defined in the following order:
7480 // a) For non-void function, the CDT is the return type.
7481 // b) If the function has any non-uniform, non-linear parameters, then the
7482 // CDT is the type of the first such parameter.
7483 // c) If the CDT determined by a) or b) above is struct, union, or class
7484 // type which is pass-by-value (except for the type that maps to the
7485 // built-in complex data type), the characteristic data type is int.
7486 // d) If none of the above three cases is applicable, the CDT is int.
7487 // The VLEN is then determined based on the CDT and the size of vector
7488 // register of that ISA for which current vector version is generated. The
7489 // VLEN is computed using the formula below:
7490 // VLEN = sizeof(vector_register) / sizeof(CDT),
7491 // where vector register size specified in section 3.2.1 Registers and the
7492 // Stack Frame of original AMD64 ABI document.
7493 QualType RetType = FD->getReturnType();
7494 if (RetType.isNull())
7495 return 0;
7496 ASTContext &C = FD->getASTContext();
7497 QualType CDT;
7498 if (!RetType.isNull() && !RetType->isVoidType())
7499 CDT = RetType;
7500 else {
7501 unsigned Offset = 0;
7502 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7503 if (ParamAttrs[Offset].Kind == Vector)
7504 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7505 ++Offset;
7506 }
7507 if (CDT.isNull()) {
7508 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7509 if (ParamAttrs[I + Offset].Kind == Vector) {
7510 CDT = FD->getParamDecl(I)->getType();
7511 break;
7512 }
7513 }
7514 }
7515 }
7516 if (CDT.isNull())
7517 CDT = C.IntTy;
7518 CDT = CDT->getCanonicalTypeUnqualified();
7519 if (CDT->isRecordType() || CDT->isUnionType())
7520 CDT = C.IntTy;
7521 return C.getTypeSize(CDT);
7522}
7523
7524static void
7525emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007526 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007527 ArrayRef<ParamAttrTy> ParamAttrs,
7528 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7529 struct ISADataTy {
7530 char ISA;
7531 unsigned VecRegSize;
7532 };
7533 ISADataTy ISAData[] = {
7534 {
7535 'b', 128
7536 }, // SSE
7537 {
7538 'c', 256
7539 }, // AVX
7540 {
7541 'd', 256
7542 }, // AVX2
7543 {
7544 'e', 512
7545 }, // AVX512
7546 };
7547 llvm::SmallVector<char, 2> Masked;
7548 switch (State) {
7549 case OMPDeclareSimdDeclAttr::BS_Undefined:
7550 Masked.push_back('N');
7551 Masked.push_back('M');
7552 break;
7553 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7554 Masked.push_back('N');
7555 break;
7556 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7557 Masked.push_back('M');
7558 break;
7559 }
7560 for (auto Mask : Masked) {
7561 for (auto &Data : ISAData) {
7562 SmallString<256> Buffer;
7563 llvm::raw_svector_ostream Out(Buffer);
7564 Out << "_ZGV" << Data.ISA << Mask;
7565 if (!VLENVal) {
7566 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7567 evaluateCDTSize(FD, ParamAttrs));
7568 } else
7569 Out << VLENVal;
7570 for (auto &ParamAttr : ParamAttrs) {
7571 switch (ParamAttr.Kind){
7572 case LinearWithVarStride:
7573 Out << 's' << ParamAttr.StrideOrArg;
7574 break;
7575 case Linear:
7576 Out << 'l';
7577 if (!!ParamAttr.StrideOrArg)
7578 Out << ParamAttr.StrideOrArg;
7579 break;
7580 case Uniform:
7581 Out << 'u';
7582 break;
7583 case Vector:
7584 Out << 'v';
7585 break;
7586 }
7587 if (!!ParamAttr.Alignment)
7588 Out << 'a' << ParamAttr.Alignment;
7589 }
7590 Out << '_' << Fn->getName();
7591 Fn->addFnAttr(Out.str());
7592 }
7593 }
7594}
7595
7596void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7597 llvm::Function *Fn) {
7598 ASTContext &C = CGM.getContext();
7599 FD = FD->getCanonicalDecl();
7600 // Map params to their positions in function decl.
7601 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7602 if (isa<CXXMethodDecl>(FD))
7603 ParamPositions.insert({FD, 0});
7604 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007605 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007606 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7607 ++ParamPos;
7608 }
7609 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7610 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7611 // Mark uniform parameters.
7612 for (auto *E : Attr->uniforms()) {
7613 E = E->IgnoreParenImpCasts();
7614 unsigned Pos;
7615 if (isa<CXXThisExpr>(E))
7616 Pos = ParamPositions[FD];
7617 else {
7618 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7619 ->getCanonicalDecl();
7620 Pos = ParamPositions[PVD];
7621 }
7622 ParamAttrs[Pos].Kind = Uniform;
7623 }
7624 // Get alignment info.
7625 auto NI = Attr->alignments_begin();
7626 for (auto *E : Attr->aligneds()) {
7627 E = E->IgnoreParenImpCasts();
7628 unsigned Pos;
7629 QualType ParmTy;
7630 if (isa<CXXThisExpr>(E)) {
7631 Pos = ParamPositions[FD];
7632 ParmTy = E->getType();
7633 } else {
7634 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7635 ->getCanonicalDecl();
7636 Pos = ParamPositions[PVD];
7637 ParmTy = PVD->getType();
7638 }
7639 ParamAttrs[Pos].Alignment =
7640 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7641 : llvm::APSInt::getUnsigned(
7642 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7643 .getQuantity());
7644 ++NI;
7645 }
7646 // Mark linear parameters.
7647 auto SI = Attr->steps_begin();
7648 auto MI = Attr->modifiers_begin();
7649 for (auto *E : Attr->linears()) {
7650 E = E->IgnoreParenImpCasts();
7651 unsigned Pos;
7652 if (isa<CXXThisExpr>(E))
7653 Pos = ParamPositions[FD];
7654 else {
7655 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7656 ->getCanonicalDecl();
7657 Pos = ParamPositions[PVD];
7658 }
7659 auto &ParamAttr = ParamAttrs[Pos];
7660 ParamAttr.Kind = Linear;
7661 if (*SI) {
7662 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7663 Expr::SE_AllowSideEffects)) {
7664 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7665 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7666 ParamAttr.Kind = LinearWithVarStride;
7667 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7668 ParamPositions[StridePVD->getCanonicalDecl()]);
7669 }
7670 }
7671 }
7672 }
7673 ++SI;
7674 ++MI;
7675 }
7676 llvm::APSInt VLENVal;
7677 if (const Expr *VLEN = Attr->getSimdlen())
7678 VLENVal = VLEN->EvaluateKnownConstInt(C);
7679 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7680 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7681 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7682 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7683 }
7684}
Alexey Bataev8b427062016-05-25 12:36:08 +00007685
7686namespace {
7687/// Cleanup action for doacross support.
7688class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7689public:
7690 static const int DoacrossFinArgs = 2;
7691
7692private:
7693 llvm::Value *RTLFn;
7694 llvm::Value *Args[DoacrossFinArgs];
7695
7696public:
7697 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7698 : RTLFn(RTLFn) {
7699 assert(CallArgs.size() == DoacrossFinArgs);
7700 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7701 }
7702 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7703 if (!CGF.HaveInsertPoint())
7704 return;
7705 CGF.EmitRuntimeCall(RTLFn, Args);
7706 }
7707};
7708} // namespace
7709
7710void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7711 const OMPLoopDirective &D) {
7712 if (!CGF.HaveInsertPoint())
7713 return;
7714
7715 ASTContext &C = CGM.getContext();
7716 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7717 RecordDecl *RD;
7718 if (KmpDimTy.isNull()) {
7719 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7720 // kmp_int64 lo; // lower
7721 // kmp_int64 up; // upper
7722 // kmp_int64 st; // stride
7723 // };
7724 RD = C.buildImplicitRecord("kmp_dim");
7725 RD->startDefinition();
7726 addFieldToRecordDecl(C, RD, Int64Ty);
7727 addFieldToRecordDecl(C, RD, Int64Ty);
7728 addFieldToRecordDecl(C, RD, Int64Ty);
7729 RD->completeDefinition();
7730 KmpDimTy = C.getRecordType(RD);
7731 } else
7732 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7733
7734 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7735 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7736 enum { LowerFD = 0, UpperFD, StrideFD };
7737 // Fill dims with data.
7738 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7739 // dims.upper = num_iterations;
7740 LValue UpperLVal =
7741 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7742 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7743 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7744 Int64Ty, D.getNumIterations()->getExprLoc());
7745 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7746 // dims.stride = 1;
7747 LValue StrideLVal =
7748 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7749 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7750 StrideLVal);
7751
7752 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7753 // kmp_int32 num_dims, struct kmp_dim * dims);
7754 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7755 getThreadID(CGF, D.getLocStart()),
7756 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7757 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7758 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7759
7760 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7761 CGF.EmitRuntimeCall(RTLFn, Args);
7762 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7763 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7764 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7765 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7766 llvm::makeArrayRef(FiniArgs));
7767}
7768
7769void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7770 const OMPDependClause *C) {
7771 QualType Int64Ty =
7772 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7773 const Expr *CounterVal = C->getCounterValue();
7774 assert(CounterVal);
7775 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7776 CounterVal->getType(), Int64Ty,
7777 CounterVal->getExprLoc());
7778 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7779 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7780 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7781 getThreadID(CGF, C->getLocStart()),
7782 CntAddr.getPointer()};
7783 llvm::Value *RTLFn;
7784 if (C->getDependencyKind() == OMPC_DEPEND_source)
7785 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7786 else {
7787 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7788 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7789 }
7790 CGF.EmitRuntimeCall(RTLFn, Args);
7791}
7792
Alexey Bataev3c595a62017-08-14 15:01:03 +00007793void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7794 ArrayRef<llvm::Value *> Args,
7795 SourceLocation Loc) const {
7796 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7797
7798 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007799 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007800 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007801 return;
7802 }
7803 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007804 CGF.EmitRuntimeCall(Callee, Args);
7805}
7806
7807void CGOpenMPRuntime::emitOutlinedFunctionCall(
7808 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7809 ArrayRef<llvm::Value *> Args) const {
7810 assert(Loc.isValid() && "Outlined function call location must be valid.");
7811 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007812}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007813
7814Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7815 const VarDecl *NativeParam,
7816 const VarDecl *TargetParam) const {
7817 return CGF.GetAddrOfLocalVar(NativeParam);
7818}